1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements decl-related attribute processing.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.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/RecursiveASTVisitor.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/DelayedDiagnostic.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedAttr.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "llvm/ADT/Optional.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/IR/Assumptions.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/raw_ostream.h"
45 
46 using namespace clang;
47 using namespace sema;
48 
49 namespace AttributeLangSupport {
50   enum LANG {
51     C,
52     Cpp,
53     ObjC
54   };
55 } // end namespace AttributeLangSupport
56 
57 //===----------------------------------------------------------------------===//
58 //  Helper functions
59 //===----------------------------------------------------------------------===//
60 
61 /// isFunctionOrMethod - Return true if the given decl has function
62 /// type (function or function-typed variable) or an Objective-C
63 /// method.
64 static bool isFunctionOrMethod(const Decl *D) {
65   return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
66 }
67 
68 /// Return true if the given decl has function type (function or
69 /// function-typed variable) or an Objective-C method or a block.
70 static bool isFunctionOrMethodOrBlock(const Decl *D) {
71   return isFunctionOrMethod(D) || isa<BlockDecl>(D);
72 }
73 
74 /// Return true if the given decl has a declarator that should have
75 /// been processed by Sema::GetTypeForDeclarator.
76 static bool hasDeclarator(const Decl *D) {
77   // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
78   return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
79          isa<ObjCPropertyDecl>(D);
80 }
81 
82 /// hasFunctionProto - Return true if the given decl has a argument
83 /// information. This decl should have already passed
84 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
85 static bool hasFunctionProto(const Decl *D) {
86   if (const FunctionType *FnTy = D->getFunctionType())
87     return isa<FunctionProtoType>(FnTy);
88   return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
89 }
90 
91 /// getFunctionOrMethodNumParams - Return number of function or method
92 /// parameters. It is an error to call this on a K&R function (use
93 /// hasFunctionProto first).
94 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
95   if (const FunctionType *FnTy = D->getFunctionType())
96     return cast<FunctionProtoType>(FnTy)->getNumParams();
97   if (const auto *BD = dyn_cast<BlockDecl>(D))
98     return BD->getNumParams();
99   return cast<ObjCMethodDecl>(D)->param_size();
100 }
101 
102 static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
103                                                    unsigned Idx) {
104   if (const auto *FD = dyn_cast<FunctionDecl>(D))
105     return FD->getParamDecl(Idx);
106   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
107     return MD->getParamDecl(Idx);
108   if (const auto *BD = dyn_cast<BlockDecl>(D))
109     return BD->getParamDecl(Idx);
110   return nullptr;
111 }
112 
113 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
114   if (const FunctionType *FnTy = D->getFunctionType())
115     return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
116   if (const auto *BD = dyn_cast<BlockDecl>(D))
117     return BD->getParamDecl(Idx)->getType();
118 
119   return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
120 }
121 
122 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
123   if (auto *PVD = getFunctionOrMethodParam(D, Idx))
124     return PVD->getSourceRange();
125   return SourceRange();
126 }
127 
128 static QualType getFunctionOrMethodResultType(const Decl *D) {
129   if (const FunctionType *FnTy = D->getFunctionType())
130     return FnTy->getReturnType();
131   return cast<ObjCMethodDecl>(D)->getReturnType();
132 }
133 
134 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
135   if (const auto *FD = dyn_cast<FunctionDecl>(D))
136     return FD->getReturnTypeSourceRange();
137   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
138     return MD->getReturnTypeSourceRange();
139   return SourceRange();
140 }
141 
142 static bool isFunctionOrMethodVariadic(const Decl *D) {
143   if (const FunctionType *FnTy = D->getFunctionType())
144     return cast<FunctionProtoType>(FnTy)->isVariadic();
145   if (const auto *BD = dyn_cast<BlockDecl>(D))
146     return BD->isVariadic();
147   return cast<ObjCMethodDecl>(D)->isVariadic();
148 }
149 
150 static bool isInstanceMethod(const Decl *D) {
151   if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
152     return MethodDecl->isInstance();
153   return false;
154 }
155 
156 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
157   const auto *PT = T->getAs<ObjCObjectPointerType>();
158   if (!PT)
159     return false;
160 
161   ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
162   if (!Cls)
163     return false;
164 
165   IdentifierInfo* ClsName = Cls->getIdentifier();
166 
167   // FIXME: Should we walk the chain of classes?
168   return ClsName == &Ctx.Idents.get("NSString") ||
169          ClsName == &Ctx.Idents.get("NSMutableString");
170 }
171 
172 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
173   const auto *PT = T->getAs<PointerType>();
174   if (!PT)
175     return false;
176 
177   const auto *RT = PT->getPointeeType()->getAs<RecordType>();
178   if (!RT)
179     return false;
180 
181   const RecordDecl *RD = RT->getDecl();
182   if (RD->getTagKind() != TTK_Struct)
183     return false;
184 
185   return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
186 }
187 
188 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
189   // FIXME: Include the type in the argument list.
190   return AL.getNumArgs() + AL.hasParsedType();
191 }
192 
193 template <typename Compare>
194 static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL,
195                                       unsigned Num, unsigned Diag,
196                                       Compare Comp) {
197   if (Comp(getNumAttributeArgs(AL), Num)) {
198     S.Diag(AL.getLoc(), Diag) << AL << Num;
199     return false;
200   }
201 
202   return true;
203 }
204 
205 /// Check if the attribute has exactly as many args as Num. May
206 /// output an error.
207 static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) {
208   return checkAttributeNumArgsImpl(S, AL, Num,
209                                    diag::err_attribute_wrong_number_arguments,
210                                    std::not_equal_to<unsigned>());
211 }
212 
213 /// Check if the attribute has at least as many args as Num. May
214 /// output an error.
215 static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL,
216                                          unsigned Num) {
217   return checkAttributeNumArgsImpl(S, AL, Num,
218                                    diag::err_attribute_too_few_arguments,
219                                    std::less<unsigned>());
220 }
221 
222 /// Check if the attribute has at most as many args as Num. May
223 /// output an error.
224 static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL,
225                                         unsigned Num) {
226   return checkAttributeNumArgsImpl(S, AL, Num,
227                                    diag::err_attribute_too_many_arguments,
228                                    std::greater<unsigned>());
229 }
230 
231 /// A helper function to provide Attribute Location for the Attr types
232 /// AND the ParsedAttr.
233 template <typename AttrInfo>
234 static std::enable_if_t<std::is_base_of<Attr, AttrInfo>::value, SourceLocation>
235 getAttrLoc(const AttrInfo &AL) {
236   return AL.getLocation();
237 }
238 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
239 
240 /// If Expr is a valid integer constant, get the value of the integer
241 /// expression and return success or failure. May output an error.
242 ///
243 /// Negative argument is implicitly converted to unsigned, unless
244 /// \p StrictlyUnsigned is true.
245 template <typename AttrInfo>
246 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
247                                 uint32_t &Val, unsigned Idx = UINT_MAX,
248                                 bool StrictlyUnsigned = false) {
249   Optional<llvm::APSInt> I = llvm::APSInt(32);
250   if (Expr->isTypeDependent() || Expr->isValueDependent() ||
251       !(I = Expr->getIntegerConstantExpr(S.Context))) {
252     if (Idx != UINT_MAX)
253       S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
254           << &AI << Idx << AANT_ArgumentIntegerConstant
255           << Expr->getSourceRange();
256     else
257       S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
258           << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
259     return false;
260   }
261 
262   if (!I->isIntN(32)) {
263     S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
264         << I->toString(10, false) << 32 << /* Unsigned */ 1;
265     return false;
266   }
267 
268   if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
269     S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
270         << &AI << /*non-negative*/ 1;
271     return false;
272   }
273 
274   Val = (uint32_t)I->getZExtValue();
275   return true;
276 }
277 
278 /// Wrapper around checkUInt32Argument, with an extra check to be sure
279 /// that the result will fit into a regular (signed) int. All args have the same
280 /// purpose as they do in checkUInt32Argument.
281 template <typename AttrInfo>
282 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
283                                      int &Val, unsigned Idx = UINT_MAX) {
284   uint32_t UVal;
285   if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
286     return false;
287 
288   if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
289     llvm::APSInt I(32); // for toString
290     I = UVal;
291     S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
292         << I.toString(10, false) << 32 << /* Unsigned */ 0;
293     return false;
294   }
295 
296   Val = UVal;
297   return true;
298 }
299 
300 /// Diagnose mutually exclusive attributes when present on a given
301 /// declaration. Returns true if diagnosed.
302 template <typename AttrTy>
303 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
304   if (const auto *A = D->getAttr<AttrTy>()) {
305     S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
306     S.Diag(A->getLocation(), diag::note_conflicting_attribute);
307     return true;
308   }
309   return false;
310 }
311 
312 template <typename AttrTy>
313 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
314   if (const auto *A = D->getAttr<AttrTy>()) {
315     S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
316                                                                       << A;
317     S.Diag(A->getLocation(), diag::note_conflicting_attribute);
318     return true;
319   }
320   return false;
321 }
322 
323 /// Check if IdxExpr is a valid parameter index for a function or
324 /// instance method D.  May output an error.
325 ///
326 /// \returns true if IdxExpr is a valid index.
327 template <typename AttrInfo>
328 static bool checkFunctionOrMethodParameterIndex(
329     Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
330     const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
331   assert(isFunctionOrMethodOrBlock(D));
332 
333   // In C++ the implicit 'this' function parameter also counts.
334   // Parameters are counted from one.
335   bool HP = hasFunctionProto(D);
336   bool HasImplicitThisParam = isInstanceMethod(D);
337   bool IV = HP && isFunctionOrMethodVariadic(D);
338   unsigned NumParams =
339       (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
340 
341   Optional<llvm::APSInt> IdxInt;
342   if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
343       !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) {
344     S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
345         << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
346         << IdxExpr->getSourceRange();
347     return false;
348   }
349 
350   unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
351   if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
352     S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
353         << &AI << AttrArgNum << IdxExpr->getSourceRange();
354     return false;
355   }
356   if (HasImplicitThisParam && !CanIndexImplicitThis) {
357     if (IdxSource == 1) {
358       S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
359           << &AI << IdxExpr->getSourceRange();
360       return false;
361     }
362   }
363 
364   Idx = ParamIdx(IdxSource, D);
365   return true;
366 }
367 
368 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
369 /// If not emit an error and return false. If the argument is an identifier it
370 /// will emit an error with a fixit hint and treat it as if it was a string
371 /// literal.
372 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
373                                           StringRef &Str,
374                                           SourceLocation *ArgLocation) {
375   // Look for identifiers. If we have one emit a hint to fix it to a literal.
376   if (AL.isArgIdent(ArgNum)) {
377     IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
378     Diag(Loc->Loc, diag::err_attribute_argument_type)
379         << AL << AANT_ArgumentString
380         << FixItHint::CreateInsertion(Loc->Loc, "\"")
381         << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
382     Str = Loc->Ident->getName();
383     if (ArgLocation)
384       *ArgLocation = Loc->Loc;
385     return true;
386   }
387 
388   // Now check for an actual string literal.
389   Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
390   const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
391   if (ArgLocation)
392     *ArgLocation = ArgExpr->getBeginLoc();
393 
394   if (!Literal || !Literal->isAscii()) {
395     Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
396         << AL << AANT_ArgumentString;
397     return false;
398   }
399 
400   Str = Literal->getString();
401   return true;
402 }
403 
404 /// Applies the given attribute to the Decl without performing any
405 /// additional semantic checking.
406 template <typename AttrType>
407 static void handleSimpleAttribute(Sema &S, Decl *D,
408                                   const AttributeCommonInfo &CI) {
409   D->addAttr(::new (S.Context) AttrType(S.Context, CI));
410 }
411 
412 template <typename... DiagnosticArgs>
413 static const Sema::SemaDiagnosticBuilder&
414 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
415   return Bldr;
416 }
417 
418 template <typename T, typename... DiagnosticArgs>
419 static const Sema::SemaDiagnosticBuilder&
420 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
421                   DiagnosticArgs &&... ExtraArgs) {
422   return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
423                            std::forward<DiagnosticArgs>(ExtraArgs)...);
424 }
425 
426 /// Add an attribute {@code AttrType} to declaration {@code D}, provided that
427 /// {@code PassesCheck} is true.
428 /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters
429 /// specified in {@code ExtraArgs}.
430 template <typename AttrType, typename... DiagnosticArgs>
431 static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D,
432                                             const AttributeCommonInfo &CI,
433                                             bool PassesCheck, unsigned DiagID,
434                                             DiagnosticArgs &&... ExtraArgs) {
435   if (!PassesCheck) {
436     Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
437     appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
438     return;
439   }
440   handleSimpleAttribute<AttrType>(S, D, CI);
441 }
442 
443 template <typename AttrType>
444 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
445                                                 const ParsedAttr &AL) {
446   handleSimpleAttribute<AttrType>(S, D, AL);
447 }
448 
449 /// Applies the given attribute to the Decl so long as the Decl doesn't
450 /// already have one of the given incompatible attributes.
451 template <typename AttrType, typename IncompatibleAttrType,
452           typename... IncompatibleAttrTypes>
453 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
454                                                 const ParsedAttr &AL) {
455   if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL))
456     return;
457   handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
458                                                                           AL);
459 }
460 
461 /// Check if the passed-in expression is of type int or bool.
462 static bool isIntOrBool(Expr *Exp) {
463   QualType QT = Exp->getType();
464   return QT->isBooleanType() || QT->isIntegerType();
465 }
466 
467 
468 // Check to see if the type is a smart pointer of some kind.  We assume
469 // it's a smart pointer if it defines both operator-> and operator*.
470 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
471   auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
472                                           OverloadedOperatorKind Op) {
473     DeclContextLookupResult Result =
474         Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
475     return !Result.empty();
476   };
477 
478   const RecordDecl *Record = RT->getDecl();
479   bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
480   bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
481   if (foundStarOperator && foundArrowOperator)
482     return true;
483 
484   const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
485   if (!CXXRecord)
486     return false;
487 
488   for (auto BaseSpecifier : CXXRecord->bases()) {
489     if (!foundStarOperator)
490       foundStarOperator = IsOverloadedOperatorPresent(
491           BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
492     if (!foundArrowOperator)
493       foundArrowOperator = IsOverloadedOperatorPresent(
494           BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
495   }
496 
497   if (foundStarOperator && foundArrowOperator)
498     return true;
499 
500   return false;
501 }
502 
503 /// Check if passed in Decl is a pointer type.
504 /// Note that this function may produce an error message.
505 /// \return true if the Decl is a pointer type; false otherwise
506 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
507                                        const ParsedAttr &AL) {
508   const auto *VD = cast<ValueDecl>(D);
509   QualType QT = VD->getType();
510   if (QT->isAnyPointerType())
511     return true;
512 
513   if (const auto *RT = QT->getAs<RecordType>()) {
514     // If it's an incomplete type, it could be a smart pointer; skip it.
515     // (We don't want to force template instantiation if we can avoid it,
516     // since that would alter the order in which templates are instantiated.)
517     if (RT->isIncompleteType())
518       return true;
519 
520     if (threadSafetyCheckIsSmartPointer(S, RT))
521       return true;
522   }
523 
524   S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
525   return false;
526 }
527 
528 /// Checks that the passed in QualType either is of RecordType or points
529 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
530 static const RecordType *getRecordType(QualType QT) {
531   if (const auto *RT = QT->getAs<RecordType>())
532     return RT;
533 
534   // Now check if we point to record type.
535   if (const auto *PT = QT->getAs<PointerType>())
536     return PT->getPointeeType()->getAs<RecordType>();
537 
538   return nullptr;
539 }
540 
541 template <typename AttrType>
542 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
543   // Check if the record itself has the attribute.
544   if (RD->hasAttr<AttrType>())
545     return true;
546 
547   // Else check if any base classes have the attribute.
548   if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
549     CXXBasePaths BPaths(false, false);
550     if (CRD->lookupInBases(
551             [](const CXXBaseSpecifier *BS, CXXBasePath &) {
552               const auto &Ty = *BS->getType();
553               // If it's type-dependent, we assume it could have the attribute.
554               if (Ty.isDependentType())
555                 return true;
556               return Ty.castAs<RecordType>()->getDecl()->hasAttr<AttrType>();
557             },
558             BPaths, true))
559       return true;
560   }
561   return false;
562 }
563 
564 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
565   const RecordType *RT = getRecordType(Ty);
566 
567   if (!RT)
568     return false;
569 
570   // Don't check for the capability if the class hasn't been defined yet.
571   if (RT->isIncompleteType())
572     return true;
573 
574   // Allow smart pointers to be used as capability objects.
575   // FIXME -- Check the type that the smart pointer points to.
576   if (threadSafetyCheckIsSmartPointer(S, RT))
577     return true;
578 
579   return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
580 }
581 
582 static bool checkTypedefTypeForCapability(QualType Ty) {
583   const auto *TD = Ty->getAs<TypedefType>();
584   if (!TD)
585     return false;
586 
587   TypedefNameDecl *TN = TD->getDecl();
588   if (!TN)
589     return false;
590 
591   return TN->hasAttr<CapabilityAttr>();
592 }
593 
594 static bool typeHasCapability(Sema &S, QualType Ty) {
595   if (checkTypedefTypeForCapability(Ty))
596     return true;
597 
598   if (checkRecordTypeForCapability(S, Ty))
599     return true;
600 
601   return false;
602 }
603 
604 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
605   // Capability expressions are simple expressions involving the boolean logic
606   // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
607   // a DeclRefExpr is found, its type should be checked to determine whether it
608   // is a capability or not.
609 
610   if (const auto *E = dyn_cast<CastExpr>(Ex))
611     return isCapabilityExpr(S, E->getSubExpr());
612   else if (const auto *E = dyn_cast<ParenExpr>(Ex))
613     return isCapabilityExpr(S, E->getSubExpr());
614   else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
615     if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
616         E->getOpcode() == UO_Deref)
617       return isCapabilityExpr(S, E->getSubExpr());
618     return false;
619   } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
620     if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
621       return isCapabilityExpr(S, E->getLHS()) &&
622              isCapabilityExpr(S, E->getRHS());
623     return false;
624   }
625 
626   return typeHasCapability(S, Ex->getType());
627 }
628 
629 /// Checks that all attribute arguments, starting from Sidx, resolve to
630 /// a capability object.
631 /// \param Sidx The attribute argument index to start checking with.
632 /// \param ParamIdxOk Whether an argument can be indexing into a function
633 /// parameter list.
634 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
635                                            const ParsedAttr &AL,
636                                            SmallVectorImpl<Expr *> &Args,
637                                            unsigned Sidx = 0,
638                                            bool ParamIdxOk = false) {
639   if (Sidx == AL.getNumArgs()) {
640     // If we don't have any capability arguments, the attribute implicitly
641     // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
642     // a non-static method, and that the class is a (scoped) capability.
643     const auto *MD = dyn_cast<const CXXMethodDecl>(D);
644     if (MD && !MD->isStatic()) {
645       const CXXRecordDecl *RD = MD->getParent();
646       // FIXME -- need to check this again on template instantiation
647       if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
648           !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
649         S.Diag(AL.getLoc(),
650                diag::warn_thread_attribute_not_on_capability_member)
651             << AL << MD->getParent();
652     } else {
653       S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
654           << AL;
655     }
656   }
657 
658   for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
659     Expr *ArgExp = AL.getArgAsExpr(Idx);
660 
661     if (ArgExp->isTypeDependent()) {
662       // FIXME -- need to check this again on template instantiation
663       Args.push_back(ArgExp);
664       continue;
665     }
666 
667     if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
668       if (StrLit->getLength() == 0 ||
669           (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
670         // Pass empty strings to the analyzer without warnings.
671         // Treat "*" as the universal lock.
672         Args.push_back(ArgExp);
673         continue;
674       }
675 
676       // We allow constant strings to be used as a placeholder for expressions
677       // that are not valid C++ syntax, but warn that they are ignored.
678       S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
679       Args.push_back(ArgExp);
680       continue;
681     }
682 
683     QualType ArgTy = ArgExp->getType();
684 
685     // A pointer to member expression of the form  &MyClass::mu is treated
686     // specially -- we need to look at the type of the member.
687     if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
688       if (UOp->getOpcode() == UO_AddrOf)
689         if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
690           if (DRE->getDecl()->isCXXInstanceMember())
691             ArgTy = DRE->getDecl()->getType();
692 
693     // First see if we can just cast to record type, or pointer to record type.
694     const RecordType *RT = getRecordType(ArgTy);
695 
696     // Now check if we index into a record type function param.
697     if(!RT && ParamIdxOk) {
698       const auto *FD = dyn_cast<FunctionDecl>(D);
699       const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
700       if(FD && IL) {
701         unsigned int NumParams = FD->getNumParams();
702         llvm::APInt ArgValue = IL->getValue();
703         uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
704         uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
705         if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
706           S.Diag(AL.getLoc(),
707                  diag::err_attribute_argument_out_of_bounds_extra_info)
708               << AL << Idx + 1 << NumParams;
709           continue;
710         }
711         ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
712       }
713     }
714 
715     // If the type does not have a capability, see if the components of the
716     // expression have capabilities. This allows for writing C code where the
717     // capability may be on the type, and the expression is a capability
718     // boolean logic expression. Eg) requires_capability(A || B && !C)
719     if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
720       S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
721           << AL << ArgTy;
722 
723     Args.push_back(ArgExp);
724   }
725 }
726 
727 //===----------------------------------------------------------------------===//
728 // Attribute Implementations
729 //===----------------------------------------------------------------------===//
730 
731 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
732   if (!threadSafetyCheckIsPointer(S, D, AL))
733     return;
734 
735   D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
736 }
737 
738 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
739                                      Expr *&Arg) {
740   SmallVector<Expr *, 1> Args;
741   // check that all arguments are lockable objects
742   checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
743   unsigned Size = Args.size();
744   if (Size != 1)
745     return false;
746 
747   Arg = Args[0];
748 
749   return true;
750 }
751 
752 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
753   Expr *Arg = nullptr;
754   if (!checkGuardedByAttrCommon(S, D, AL, Arg))
755     return;
756 
757   D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
758 }
759 
760 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
761   Expr *Arg = nullptr;
762   if (!checkGuardedByAttrCommon(S, D, AL, Arg))
763     return;
764 
765   if (!threadSafetyCheckIsPointer(S, D, AL))
766     return;
767 
768   D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
769 }
770 
771 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
772                                         SmallVectorImpl<Expr *> &Args) {
773   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
774     return false;
775 
776   // Check that this attribute only applies to lockable types.
777   QualType QT = cast<ValueDecl>(D)->getType();
778   if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
779     S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
780     return false;
781   }
782 
783   // Check that all arguments are lockable objects.
784   checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
785   if (Args.empty())
786     return false;
787 
788   return true;
789 }
790 
791 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
792   SmallVector<Expr *, 1> Args;
793   if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
794     return;
795 
796   Expr **StartArg = &Args[0];
797   D->addAttr(::new (S.Context)
798                  AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
799 }
800 
801 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
802   SmallVector<Expr *, 1> Args;
803   if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
804     return;
805 
806   Expr **StartArg = &Args[0];
807   D->addAttr(::new (S.Context)
808                  AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
809 }
810 
811 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
812                                    SmallVectorImpl<Expr *> &Args) {
813   // zero or more arguments ok
814   // check that all arguments are lockable objects
815   checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
816 
817   return true;
818 }
819 
820 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
821   SmallVector<Expr *, 1> Args;
822   if (!checkLockFunAttrCommon(S, D, AL, Args))
823     return;
824 
825   unsigned Size = Args.size();
826   Expr **StartArg = Size == 0 ? nullptr : &Args[0];
827   D->addAttr(::new (S.Context)
828                  AssertSharedLockAttr(S.Context, AL, StartArg, Size));
829 }
830 
831 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
832                                           const ParsedAttr &AL) {
833   SmallVector<Expr *, 1> Args;
834   if (!checkLockFunAttrCommon(S, D, AL, Args))
835     return;
836 
837   unsigned Size = Args.size();
838   Expr **StartArg = Size == 0 ? nullptr : &Args[0];
839   D->addAttr(::new (S.Context)
840                  AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
841 }
842 
843 /// Checks to be sure that the given parameter number is in bounds, and
844 /// is an integral type. Will emit appropriate diagnostics if this returns
845 /// false.
846 ///
847 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
848 template <typename AttrInfo>
849 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
850                                     const AttrInfo &AI, unsigned AttrArgNo) {
851   assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
852   Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
853   ParamIdx Idx;
854   if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg,
855                                            Idx))
856     return false;
857 
858   const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex());
859   if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
860     SourceLocation SrcLoc = AttrArg->getBeginLoc();
861     S.Diag(SrcLoc, diag::err_attribute_integers_only)
862         << AI << Param->getSourceRange();
863     return false;
864   }
865   return true;
866 }
867 
868 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
869   if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
870       !checkAttributeAtMostNumArgs(S, AL, 2))
871     return;
872 
873   const auto *FD = cast<FunctionDecl>(D);
874   if (!FD->getReturnType()->isPointerType()) {
875     S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
876     return;
877   }
878 
879   const Expr *SizeExpr = AL.getArgAsExpr(0);
880   int SizeArgNoVal;
881   // Parameter indices are 1-indexed, hence Index=1
882   if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
883     return;
884   if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0))
885     return;
886   ParamIdx SizeArgNo(SizeArgNoVal, D);
887 
888   ParamIdx NumberArgNo;
889   if (AL.getNumArgs() == 2) {
890     const Expr *NumberExpr = AL.getArgAsExpr(1);
891     int Val;
892     // Parameter indices are 1-based, hence Index=2
893     if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
894       return;
895     if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1))
896       return;
897     NumberArgNo = ParamIdx(Val, D);
898   }
899 
900   D->addAttr(::new (S.Context)
901                  AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
902 }
903 
904 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
905                                       SmallVectorImpl<Expr *> &Args) {
906   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
907     return false;
908 
909   if (!isIntOrBool(AL.getArgAsExpr(0))) {
910     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
911         << AL << 1 << AANT_ArgumentIntOrBool;
912     return false;
913   }
914 
915   // check that all arguments are lockable objects
916   checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
917 
918   return true;
919 }
920 
921 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
922                                             const ParsedAttr &AL) {
923   SmallVector<Expr*, 2> Args;
924   if (!checkTryLockFunAttrCommon(S, D, AL, Args))
925     return;
926 
927   D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
928       S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
929 }
930 
931 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
932                                                const ParsedAttr &AL) {
933   SmallVector<Expr*, 2> Args;
934   if (!checkTryLockFunAttrCommon(S, D, AL, Args))
935     return;
936 
937   D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
938       S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
939 }
940 
941 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
942   // check that the argument is lockable object
943   SmallVector<Expr*, 1> Args;
944   checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
945   unsigned Size = Args.size();
946   if (Size == 0)
947     return;
948 
949   D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
950 }
951 
952 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
953   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
954     return;
955 
956   // check that all arguments are lockable objects
957   SmallVector<Expr*, 1> Args;
958   checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
959   unsigned Size = Args.size();
960   if (Size == 0)
961     return;
962   Expr **StartArg = &Args[0];
963 
964   D->addAttr(::new (S.Context)
965                  LocksExcludedAttr(S.Context, AL, StartArg, Size));
966 }
967 
968 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
969                                        Expr *&Cond, StringRef &Msg) {
970   Cond = AL.getArgAsExpr(0);
971   if (!Cond->isTypeDependent()) {
972     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
973     if (Converted.isInvalid())
974       return false;
975     Cond = Converted.get();
976   }
977 
978   if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
979     return false;
980 
981   if (Msg.empty())
982     Msg = "<no message provided>";
983 
984   SmallVector<PartialDiagnosticAt, 8> Diags;
985   if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
986       !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
987                                                 Diags)) {
988     S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
989     for (const PartialDiagnosticAt &PDiag : Diags)
990       S.Diag(PDiag.first, PDiag.second);
991     return false;
992   }
993   return true;
994 }
995 
996 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
997   S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
998 
999   Expr *Cond;
1000   StringRef Msg;
1001   if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1002     D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
1003 }
1004 
1005 namespace {
1006 /// Determines if a given Expr references any of the given function's
1007 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
1008 class ArgumentDependenceChecker
1009     : public RecursiveASTVisitor<ArgumentDependenceChecker> {
1010 #ifndef NDEBUG
1011   const CXXRecordDecl *ClassType;
1012 #endif
1013   llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
1014   bool Result;
1015 
1016 public:
1017   ArgumentDependenceChecker(const FunctionDecl *FD) {
1018 #ifndef NDEBUG
1019     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1020       ClassType = MD->getParent();
1021     else
1022       ClassType = nullptr;
1023 #endif
1024     Parms.insert(FD->param_begin(), FD->param_end());
1025   }
1026 
1027   bool referencesArgs(Expr *E) {
1028     Result = false;
1029     TraverseStmt(E);
1030     return Result;
1031   }
1032 
1033   bool VisitCXXThisExpr(CXXThisExpr *E) {
1034     assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1035            "`this` doesn't refer to the enclosing class?");
1036     Result = true;
1037     return false;
1038   }
1039 
1040   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1041     if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1042       if (Parms.count(PVD)) {
1043         Result = true;
1044         return false;
1045       }
1046     return true;
1047   }
1048 };
1049 }
1050 
1051 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1052   S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1053 
1054   Expr *Cond;
1055   StringRef Msg;
1056   if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1057     return;
1058 
1059   StringRef DiagTypeStr;
1060   if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1061     return;
1062 
1063   DiagnoseIfAttr::DiagnosticType DiagType;
1064   if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1065     S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1066            diag::err_diagnose_if_invalid_diagnostic_type);
1067     return;
1068   }
1069 
1070   bool ArgDependent = false;
1071   if (const auto *FD = dyn_cast<FunctionDecl>(D))
1072     ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1073   D->addAttr(::new (S.Context) DiagnoseIfAttr(
1074       S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1075 }
1076 
1077 static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1078   static constexpr const StringRef kWildcard = "*";
1079 
1080   llvm::SmallVector<StringRef, 16> Names;
1081   bool HasWildcard = false;
1082 
1083   const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
1084     if (Name == kWildcard)
1085       HasWildcard = true;
1086     Names.push_back(Name);
1087   };
1088 
1089   // Add previously defined attributes.
1090   if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
1091     for (StringRef BuiltinName : NBA->builtinNames())
1092       AddBuiltinName(BuiltinName);
1093 
1094   // Add current attributes.
1095   if (AL.getNumArgs() == 0)
1096     AddBuiltinName(kWildcard);
1097   else
1098     for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
1099       StringRef BuiltinName;
1100       SourceLocation LiteralLoc;
1101       if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
1102         return;
1103 
1104       if (Builtin::Context::isBuiltinFunc(BuiltinName))
1105         AddBuiltinName(BuiltinName);
1106       else
1107         S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
1108             << BuiltinName << AL;
1109     }
1110 
1111   // Repeating the same attribute is fine.
1112   llvm::sort(Names);
1113   Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
1114 
1115   // Empty no_builtin must be on its own.
1116   if (HasWildcard && Names.size() > 1)
1117     S.Diag(D->getLocation(),
1118            diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1119         << AL;
1120 
1121   if (D->hasAttr<NoBuiltinAttr>())
1122     D->dropAttr<NoBuiltinAttr>();
1123   D->addAttr(::new (S.Context)
1124                  NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1125 }
1126 
1127 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1128   if (D->hasAttr<PassObjectSizeAttr>()) {
1129     S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1130     return;
1131   }
1132 
1133   Expr *E = AL.getArgAsExpr(0);
1134   uint32_t Type;
1135   if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1136     return;
1137 
1138   // pass_object_size's argument is passed in as the second argument of
1139   // __builtin_object_size. So, it has the same constraints as that second
1140   // argument; namely, it must be in the range [0, 3].
1141   if (Type > 3) {
1142     S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1143         << AL << 0 << 3 << E->getSourceRange();
1144     return;
1145   }
1146 
1147   // pass_object_size is only supported on constant pointer parameters; as a
1148   // kindness to users, we allow the parameter to be non-const for declarations.
1149   // At this point, we have no clue if `D` belongs to a function declaration or
1150   // definition, so we defer the constness check until later.
1151   if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1152     S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1153     return;
1154   }
1155 
1156   D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1157 }
1158 
1159 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1160   ConsumableAttr::ConsumedState DefaultState;
1161 
1162   if (AL.isArgIdent(0)) {
1163     IdentifierLoc *IL = AL.getArgAsIdent(0);
1164     if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1165                                                    DefaultState)) {
1166       S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1167                                                                << IL->Ident;
1168       return;
1169     }
1170   } else {
1171     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1172         << AL << AANT_ArgumentIdentifier;
1173     return;
1174   }
1175 
1176   D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1177 }
1178 
1179 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1180                                     const ParsedAttr &AL) {
1181   QualType ThisType = MD->getThisType()->getPointeeType();
1182 
1183   if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1184     if (!RD->hasAttr<ConsumableAttr>()) {
1185       S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
1186 
1187       return false;
1188     }
1189   }
1190 
1191   return true;
1192 }
1193 
1194 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1195   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1196     return;
1197 
1198   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1199     return;
1200 
1201   SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1202   for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1203     CallableWhenAttr::ConsumedState CallableState;
1204 
1205     StringRef StateString;
1206     SourceLocation Loc;
1207     if (AL.isArgIdent(ArgIndex)) {
1208       IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1209       StateString = Ident->Ident->getName();
1210       Loc = Ident->Loc;
1211     } else {
1212       if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1213         return;
1214     }
1215 
1216     if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1217                                                      CallableState)) {
1218       S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1219       return;
1220     }
1221 
1222     States.push_back(CallableState);
1223   }
1224 
1225   D->addAttr(::new (S.Context)
1226                  CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1227 }
1228 
1229 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1230   ParamTypestateAttr::ConsumedState ParamState;
1231 
1232   if (AL.isArgIdent(0)) {
1233     IdentifierLoc *Ident = AL.getArgAsIdent(0);
1234     StringRef StateString = Ident->Ident->getName();
1235 
1236     if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1237                                                        ParamState)) {
1238       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1239           << AL << StateString;
1240       return;
1241     }
1242   } else {
1243     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1244         << AL << AANT_ArgumentIdentifier;
1245     return;
1246   }
1247 
1248   // FIXME: This check is currently being done in the analysis.  It can be
1249   //        enabled here only after the parser propagates attributes at
1250   //        template specialization definition, not declaration.
1251   //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1252   //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1253   //
1254   //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1255   //    S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1256   //      ReturnType.getAsString();
1257   //    return;
1258   //}
1259 
1260   D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1261 }
1262 
1263 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1264   ReturnTypestateAttr::ConsumedState ReturnState;
1265 
1266   if (AL.isArgIdent(0)) {
1267     IdentifierLoc *IL = AL.getArgAsIdent(0);
1268     if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1269                                                         ReturnState)) {
1270       S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1271                                                                << IL->Ident;
1272       return;
1273     }
1274   } else {
1275     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1276         << AL << AANT_ArgumentIdentifier;
1277     return;
1278   }
1279 
1280   // FIXME: This check is currently being done in the analysis.  It can be
1281   //        enabled here only after the parser propagates attributes at
1282   //        template specialization definition, not declaration.
1283   //QualType ReturnType;
1284   //
1285   //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1286   //  ReturnType = Param->getType();
1287   //
1288   //} else if (const CXXConstructorDecl *Constructor =
1289   //             dyn_cast<CXXConstructorDecl>(D)) {
1290   //  ReturnType = Constructor->getThisType()->getPointeeType();
1291   //
1292   //} else {
1293   //
1294   //  ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1295   //}
1296   //
1297   //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1298   //
1299   //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1300   //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1301   //      ReturnType.getAsString();
1302   //    return;
1303   //}
1304 
1305   D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1306 }
1307 
1308 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1309   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1310     return;
1311 
1312   SetTypestateAttr::ConsumedState NewState;
1313   if (AL.isArgIdent(0)) {
1314     IdentifierLoc *Ident = AL.getArgAsIdent(0);
1315     StringRef Param = Ident->Ident->getName();
1316     if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1317       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1318                                                                   << Param;
1319       return;
1320     }
1321   } else {
1322     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1323         << AL << AANT_ArgumentIdentifier;
1324     return;
1325   }
1326 
1327   D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1328 }
1329 
1330 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1331   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1332     return;
1333 
1334   TestTypestateAttr::ConsumedState TestState;
1335   if (AL.isArgIdent(0)) {
1336     IdentifierLoc *Ident = AL.getArgAsIdent(0);
1337     StringRef Param = Ident->Ident->getName();
1338     if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1339       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1340                                                                   << Param;
1341       return;
1342     }
1343   } else {
1344     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1345         << AL << AANT_ArgumentIdentifier;
1346     return;
1347   }
1348 
1349   D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1350 }
1351 
1352 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1353   // Remember this typedef decl, we will need it later for diagnostics.
1354   S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1355 }
1356 
1357 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1358   if (auto *TD = dyn_cast<TagDecl>(D))
1359     TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1360   else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1361     bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1362                                 !FD->getType()->isIncompleteType() &&
1363                                 FD->isBitField() &&
1364                                 S.Context.getTypeAlign(FD->getType()) <= 8);
1365 
1366     if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1367       if (BitfieldByteAligned)
1368         // The PS4 target needs to maintain ABI backwards compatibility.
1369         S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1370             << AL << FD->getType();
1371       else
1372         FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1373     } else {
1374       // Report warning about changed offset in the newer compiler versions.
1375       if (BitfieldByteAligned)
1376         S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1377 
1378       FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1379     }
1380 
1381   } else
1382     S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1383 }
1384 
1385 static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1386   auto *RD = cast<CXXRecordDecl>(D);
1387   ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1388   assert(CTD && "attribute does not appertain to this declaration");
1389 
1390   ParsedType PT = AL.getTypeArg();
1391   TypeSourceInfo *TSI = nullptr;
1392   QualType T = S.GetTypeFromParser(PT, &TSI);
1393   if (!TSI)
1394     TSI = S.Context.getTrivialTypeSourceInfo(T, AL.getLoc());
1395 
1396   if (!T.hasQualifiers() && T->isTypedefNameType()) {
1397     // Find the template name, if this type names a template specialization.
1398     const TemplateDecl *Template = nullptr;
1399     if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1400             T->getAsCXXRecordDecl())) {
1401       Template = CTSD->getSpecializedTemplate();
1402     } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1403       while (TST && TST->isTypeAlias())
1404         TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1405       if (TST)
1406         Template = TST->getTemplateName().getAsTemplateDecl();
1407     }
1408 
1409     if (Template && declaresSameEntity(Template, CTD)) {
1410       D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1411       return;
1412     }
1413   }
1414 
1415   S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1416       << T << CTD;
1417   if (const auto *TT = T->getAs<TypedefType>())
1418     S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1419         << TT->getDecl();
1420 }
1421 
1422 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1423   // The IBOutlet/IBOutletCollection attributes only apply to instance
1424   // variables or properties of Objective-C classes.  The outlet must also
1425   // have an object reference type.
1426   if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1427     if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1428       S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1429           << AL << VD->getType() << 0;
1430       return false;
1431     }
1432   }
1433   else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1434     if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1435       S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1436           << AL << PD->getType() << 1;
1437       return false;
1438     }
1439   }
1440   else {
1441     S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1442     return false;
1443   }
1444 
1445   return true;
1446 }
1447 
1448 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1449   if (!checkIBOutletCommon(S, D, AL))
1450     return;
1451 
1452   D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1453 }
1454 
1455 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1456 
1457   // The iboutletcollection attribute can have zero or one arguments.
1458   if (AL.getNumArgs() > 1) {
1459     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1460     return;
1461   }
1462 
1463   if (!checkIBOutletCommon(S, D, AL))
1464     return;
1465 
1466   ParsedType PT;
1467 
1468   if (AL.hasParsedType())
1469     PT = AL.getTypeArg();
1470   else {
1471     PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1472                        S.getScopeForContext(D->getDeclContext()->getParent()));
1473     if (!PT) {
1474       S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1475       return;
1476     }
1477   }
1478 
1479   TypeSourceInfo *QTLoc = nullptr;
1480   QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1481   if (!QTLoc)
1482     QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1483 
1484   // Diagnose use of non-object type in iboutletcollection attribute.
1485   // FIXME. Gnu attribute extension ignores use of builtin types in
1486   // attributes. So, __attribute__((iboutletcollection(char))) will be
1487   // treated as __attribute__((iboutletcollection())).
1488   if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1489     S.Diag(AL.getLoc(),
1490            QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1491                                : diag::err_iboutletcollection_type) << QT;
1492     return;
1493   }
1494 
1495   D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1496 }
1497 
1498 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1499   if (RefOkay) {
1500     if (T->isReferenceType())
1501       return true;
1502   } else {
1503     T = T.getNonReferenceType();
1504   }
1505 
1506   // The nonnull attribute, and other similar attributes, can be applied to a
1507   // transparent union that contains a pointer type.
1508   if (const RecordType *UT = T->getAsUnionType()) {
1509     if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1510       RecordDecl *UD = UT->getDecl();
1511       for (const auto *I : UD->fields()) {
1512         QualType QT = I->getType();
1513         if (QT->isAnyPointerType() || QT->isBlockPointerType())
1514           return true;
1515       }
1516     }
1517   }
1518 
1519   return T->isAnyPointerType() || T->isBlockPointerType();
1520 }
1521 
1522 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1523                                 SourceRange AttrParmRange,
1524                                 SourceRange TypeRange,
1525                                 bool isReturnValue = false) {
1526   if (!S.isValidPointerAttrType(T)) {
1527     if (isReturnValue)
1528       S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1529           << AL << AttrParmRange << TypeRange;
1530     else
1531       S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1532           << AL << AttrParmRange << TypeRange << 0;
1533     return false;
1534   }
1535   return true;
1536 }
1537 
1538 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1539   SmallVector<ParamIdx, 8> NonNullArgs;
1540   for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1541     Expr *Ex = AL.getArgAsExpr(I);
1542     ParamIdx Idx;
1543     if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1544       return;
1545 
1546     // Is the function argument a pointer type?
1547     if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1548         !attrNonNullArgCheck(
1549             S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1550             Ex->getSourceRange(),
1551             getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1552       continue;
1553 
1554     NonNullArgs.push_back(Idx);
1555   }
1556 
1557   // If no arguments were specified to __attribute__((nonnull)) then all pointer
1558   // arguments have a nonnull attribute; warn if there aren't any. Skip this
1559   // check if the attribute came from a macro expansion or a template
1560   // instantiation.
1561   if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1562       !S.inTemplateInstantiation()) {
1563     bool AnyPointers = isFunctionOrMethodVariadic(D);
1564     for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1565          I != E && !AnyPointers; ++I) {
1566       QualType T = getFunctionOrMethodParamType(D, I);
1567       if (T->isDependentType() || S.isValidPointerAttrType(T))
1568         AnyPointers = true;
1569     }
1570 
1571     if (!AnyPointers)
1572       S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1573   }
1574 
1575   ParamIdx *Start = NonNullArgs.data();
1576   unsigned Size = NonNullArgs.size();
1577   llvm::array_pod_sort(Start, Start + Size);
1578   D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1579 }
1580 
1581 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1582                                        const ParsedAttr &AL) {
1583   if (AL.getNumArgs() > 0) {
1584     if (D->getFunctionType()) {
1585       handleNonNullAttr(S, D, AL);
1586     } else {
1587       S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1588         << D->getSourceRange();
1589     }
1590     return;
1591   }
1592 
1593   // Is the argument a pointer type?
1594   if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1595                            D->getSourceRange()))
1596     return;
1597 
1598   D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1599 }
1600 
1601 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1602   QualType ResultType = getFunctionOrMethodResultType(D);
1603   SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1604   if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1605                            /* isReturnValue */ true))
1606     return;
1607 
1608   D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1609 }
1610 
1611 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1612   if (D->isInvalidDecl())
1613     return;
1614 
1615   // noescape only applies to pointer types.
1616   QualType T = cast<ParmVarDecl>(D)->getType();
1617   if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1618     S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1619         << AL << AL.getRange() << 0;
1620     return;
1621   }
1622 
1623   D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1624 }
1625 
1626 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1627   Expr *E = AL.getArgAsExpr(0),
1628        *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1629   S.AddAssumeAlignedAttr(D, AL, E, OE);
1630 }
1631 
1632 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1633   S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1634 }
1635 
1636 void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
1637                                 Expr *OE) {
1638   QualType ResultType = getFunctionOrMethodResultType(D);
1639   SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1640 
1641   AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1642   SourceLocation AttrLoc = TmpAttr.getLocation();
1643 
1644   if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1645     Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1646         << &TmpAttr << TmpAttr.getRange() << SR;
1647     return;
1648   }
1649 
1650   if (!E->isValueDependent()) {
1651     Optional<llvm::APSInt> I = llvm::APSInt(64);
1652     if (!(I = E->getIntegerConstantExpr(Context))) {
1653       if (OE)
1654         Diag(AttrLoc, diag::err_attribute_argument_n_type)
1655           << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1656           << E->getSourceRange();
1657       else
1658         Diag(AttrLoc, diag::err_attribute_argument_type)
1659           << &TmpAttr << AANT_ArgumentIntegerConstant
1660           << E->getSourceRange();
1661       return;
1662     }
1663 
1664     if (!I->isPowerOf2()) {
1665       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1666         << E->getSourceRange();
1667       return;
1668     }
1669 
1670     if (*I > Sema::MaximumAlignment)
1671       Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1672           << CI.getRange() << Sema::MaximumAlignment;
1673   }
1674 
1675   if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) {
1676     Diag(AttrLoc, diag::err_attribute_argument_n_type)
1677         << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1678         << OE->getSourceRange();
1679     return;
1680   }
1681 
1682   D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1683 }
1684 
1685 void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
1686                              Expr *ParamExpr) {
1687   QualType ResultType = getFunctionOrMethodResultType(D);
1688 
1689   AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1690   SourceLocation AttrLoc = CI.getLoc();
1691 
1692   if (!ResultType->isDependentType() &&
1693       !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1694     Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1695         << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1696     return;
1697   }
1698 
1699   ParamIdx Idx;
1700   const auto *FuncDecl = cast<FunctionDecl>(D);
1701   if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1702                                            /*AttrArgNum=*/1, ParamExpr, Idx))
1703     return;
1704 
1705   QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1706   if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1707       !Ty->isAlignValT()) {
1708     Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1709         << &TmpAttr
1710         << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1711     return;
1712   }
1713 
1714   D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1715 }
1716 
1717 /// Check if \p AssumptionStr is a known assumption and warn if not.
1718 static void checkAssumptionAttr(Sema &S, SourceLocation Loc,
1719                                 StringRef AssumptionStr) {
1720   if (llvm::KnownAssumptionStrings.count(AssumptionStr))
1721     return;
1722 
1723   unsigned BestEditDistance = 3;
1724   StringRef Suggestion;
1725   for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) {
1726     unsigned EditDistance =
1727         AssumptionStr.edit_distance(KnownAssumptionIt.getKey());
1728     if (EditDistance < BestEditDistance) {
1729       Suggestion = KnownAssumptionIt.getKey();
1730       BestEditDistance = EditDistance;
1731     }
1732   }
1733 
1734   if (!Suggestion.empty())
1735     S.Diag(Loc, diag::warn_assume_attribute_string_unknown_suggested)
1736         << AssumptionStr << Suggestion;
1737   else
1738     S.Diag(Loc, diag::warn_assume_attribute_string_unknown) << AssumptionStr;
1739 }
1740 
1741 static void handleAssumumptionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1742   // Handle the case where the attribute has a text message.
1743   StringRef Str;
1744   SourceLocation AttrStrLoc;
1745   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &AttrStrLoc))
1746     return;
1747 
1748   checkAssumptionAttr(S, AttrStrLoc, Str);
1749 
1750   D->addAttr(::new (S.Context) AssumptionAttr(S.Context, AL, Str));
1751 }
1752 
1753 /// Normalize the attribute, __foo__ becomes foo.
1754 /// Returns true if normalization was applied.
1755 static bool normalizeName(StringRef &AttrName) {
1756   if (AttrName.size() > 4 && AttrName.startswith("__") &&
1757       AttrName.endswith("__")) {
1758     AttrName = AttrName.drop_front(2).drop_back(2);
1759     return true;
1760   }
1761   return false;
1762 }
1763 
1764 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1765   // This attribute must be applied to a function declaration. The first
1766   // argument to the attribute must be an identifier, the name of the resource,
1767   // for example: malloc. The following arguments must be argument indexes, the
1768   // arguments must be of integer type for Returns, otherwise of pointer type.
1769   // The difference between Holds and Takes is that a pointer may still be used
1770   // after being held. free() should be __attribute((ownership_takes)), whereas
1771   // a list append function may well be __attribute((ownership_holds)).
1772 
1773   if (!AL.isArgIdent(0)) {
1774     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1775         << AL << 1 << AANT_ArgumentIdentifier;
1776     return;
1777   }
1778 
1779   // Figure out our Kind.
1780   OwnershipAttr::OwnershipKind K =
1781       OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1782 
1783   // Check arguments.
1784   switch (K) {
1785   case OwnershipAttr::Takes:
1786   case OwnershipAttr::Holds:
1787     if (AL.getNumArgs() < 2) {
1788       S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1789       return;
1790     }
1791     break;
1792   case OwnershipAttr::Returns:
1793     if (AL.getNumArgs() > 2) {
1794       S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1795       return;
1796     }
1797     break;
1798   }
1799 
1800   IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1801 
1802   StringRef ModuleName = Module->getName();
1803   if (normalizeName(ModuleName)) {
1804     Module = &S.PP.getIdentifierTable().get(ModuleName);
1805   }
1806 
1807   SmallVector<ParamIdx, 8> OwnershipArgs;
1808   for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1809     Expr *Ex = AL.getArgAsExpr(i);
1810     ParamIdx Idx;
1811     if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1812       return;
1813 
1814     // Is the function argument a pointer type?
1815     QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1816     int Err = -1;  // No error
1817     switch (K) {
1818       case OwnershipAttr::Takes:
1819       case OwnershipAttr::Holds:
1820         if (!T->isAnyPointerType() && !T->isBlockPointerType())
1821           Err = 0;
1822         break;
1823       case OwnershipAttr::Returns:
1824         if (!T->isIntegerType())
1825           Err = 1;
1826         break;
1827     }
1828     if (-1 != Err) {
1829       S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1830                                                     << Ex->getSourceRange();
1831       return;
1832     }
1833 
1834     // Check we don't have a conflict with another ownership attribute.
1835     for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1836       // Cannot have two ownership attributes of different kinds for the same
1837       // index.
1838       if (I->getOwnKind() != K && I->args_end() !=
1839           std::find(I->args_begin(), I->args_end(), Idx)) {
1840         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1841         return;
1842       } else if (K == OwnershipAttr::Returns &&
1843                  I->getOwnKind() == OwnershipAttr::Returns) {
1844         // A returns attribute conflicts with any other returns attribute using
1845         // a different index.
1846         if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1847           S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1848               << I->args_begin()->getSourceIndex();
1849           if (I->args_size())
1850             S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1851                 << Idx.getSourceIndex() << Ex->getSourceRange();
1852           return;
1853         }
1854       }
1855     }
1856     OwnershipArgs.push_back(Idx);
1857   }
1858 
1859   ParamIdx *Start = OwnershipArgs.data();
1860   unsigned Size = OwnershipArgs.size();
1861   llvm::array_pod_sort(Start, Start + Size);
1862   D->addAttr(::new (S.Context)
1863                  OwnershipAttr(S.Context, AL, Module, Start, Size));
1864 }
1865 
1866 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1867   // Check the attribute arguments.
1868   if (AL.getNumArgs() > 1) {
1869     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1870     return;
1871   }
1872 
1873   // gcc rejects
1874   // class c {
1875   //   static int a __attribute__((weakref ("v2")));
1876   //   static int b() __attribute__((weakref ("f3")));
1877   // };
1878   // and ignores the attributes of
1879   // void f(void) {
1880   //   static int a __attribute__((weakref ("v2")));
1881   // }
1882   // we reject them
1883   const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1884   if (!Ctx->isFileContext()) {
1885     S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1886         << cast<NamedDecl>(D);
1887     return;
1888   }
1889 
1890   // The GCC manual says
1891   //
1892   // At present, a declaration to which `weakref' is attached can only
1893   // be `static'.
1894   //
1895   // It also says
1896   //
1897   // Without a TARGET,
1898   // given as an argument to `weakref' or to `alias', `weakref' is
1899   // equivalent to `weak'.
1900   //
1901   // gcc 4.4.1 will accept
1902   // int a7 __attribute__((weakref));
1903   // as
1904   // int a7 __attribute__((weak));
1905   // This looks like a bug in gcc. We reject that for now. We should revisit
1906   // it if this behaviour is actually used.
1907 
1908   // GCC rejects
1909   // static ((alias ("y"), weakref)).
1910   // Should we? How to check that weakref is before or after alias?
1911 
1912   // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1913   // of transforming it into an AliasAttr.  The WeakRefAttr never uses the
1914   // StringRef parameter it was given anyway.
1915   StringRef Str;
1916   if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1917     // GCC will accept anything as the argument of weakref. Should we
1918     // check for an existing decl?
1919     D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1920 
1921   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1922 }
1923 
1924 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1925   StringRef Str;
1926   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1927     return;
1928 
1929   // Aliases should be on declarations, not definitions.
1930   const auto *FD = cast<FunctionDecl>(D);
1931   if (FD->isThisDeclarationADefinition()) {
1932     S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1933     return;
1934   }
1935 
1936   D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1937 }
1938 
1939 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1940   StringRef Str;
1941   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1942     return;
1943 
1944   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1945     S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1946     return;
1947   }
1948   if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1949     S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1950   }
1951 
1952   // Aliases should be on declarations, not definitions.
1953   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1954     if (FD->isThisDeclarationADefinition()) {
1955       S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1956       return;
1957     }
1958   } else {
1959     const auto *VD = cast<VarDecl>(D);
1960     if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1961       S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1962       return;
1963     }
1964   }
1965 
1966   // Mark target used to prevent unneeded-internal-declaration warnings.
1967   if (!S.LangOpts.CPlusPlus) {
1968     // FIXME: demangle Str for C++, as the attribute refers to the mangled
1969     // linkage name, not the pre-mangled identifier.
1970     const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
1971     LookupResult LR(S, target, Sema::LookupOrdinaryName);
1972     if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
1973       for (NamedDecl *ND : LR)
1974         ND->markUsed(S.Context);
1975   }
1976 
1977   D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1978 }
1979 
1980 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1981   StringRef Model;
1982   SourceLocation LiteralLoc;
1983   // Check that it is a string.
1984   if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1985     return;
1986 
1987   // Check that the value.
1988   if (Model != "global-dynamic" && Model != "local-dynamic"
1989       && Model != "initial-exec" && Model != "local-exec") {
1990     S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1991     return;
1992   }
1993 
1994   D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
1995 }
1996 
1997 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1998   QualType ResultType = getFunctionOrMethodResultType(D);
1999   if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
2000     D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
2001     return;
2002   }
2003 
2004   S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
2005       << AL << getFunctionOrMethodResultSourceRange(D);
2006 }
2007 
2008 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2009   FunctionDecl *FD = cast<FunctionDecl>(D);
2010 
2011   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2012     if (MD->getParent()->isLambda()) {
2013       S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
2014       return;
2015     }
2016   }
2017 
2018   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2019     return;
2020 
2021   SmallVector<IdentifierInfo *, 8> CPUs;
2022   for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
2023     if (!AL.isArgIdent(ArgNo)) {
2024       S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
2025           << AL << AANT_ArgumentIdentifier;
2026       return;
2027     }
2028 
2029     IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
2030     StringRef CPUName = CPUArg->Ident->getName().trim();
2031 
2032     if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
2033       S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
2034           << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
2035       return;
2036     }
2037 
2038     const TargetInfo &Target = S.Context.getTargetInfo();
2039     if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
2040           return Target.CPUSpecificManglingCharacter(CPUName) ==
2041                  Target.CPUSpecificManglingCharacter(Cur->getName());
2042         })) {
2043       S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
2044       return;
2045     }
2046     CPUs.push_back(CPUArg->Ident);
2047   }
2048 
2049   FD->setIsMultiVersion(true);
2050   if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
2051     D->addAttr(::new (S.Context)
2052                    CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2053   else
2054     D->addAttr(::new (S.Context)
2055                    CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2056 }
2057 
2058 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2059   if (S.LangOpts.CPlusPlus) {
2060     S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2061         << AL << AttributeLangSupport::Cpp;
2062     return;
2063   }
2064 
2065   if (CommonAttr *CA = S.mergeCommonAttr(D, AL))
2066     D->addAttr(CA);
2067 }
2068 
2069 static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2070   if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) {
2071     S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
2072     return;
2073   }
2074 
2075   const auto *FD = cast<FunctionDecl>(D);
2076   if (!FD->isExternallyVisible()) {
2077     S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
2078     return;
2079   }
2080 
2081   D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
2082 }
2083 
2084 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2085   if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL))
2086     return;
2087 
2088   if (AL.isDeclspecAttribute()) {
2089     const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2090     const auto &Arch = Triple.getArch();
2091     if (Arch != llvm::Triple::x86 &&
2092         (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2093       S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2094           << AL << Triple.getArchName();
2095       return;
2096     }
2097   }
2098 
2099   D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2100 }
2101 
2102 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2103   if (hasDeclarator(D)) return;
2104 
2105   if (!isa<ObjCMethodDecl>(D)) {
2106     S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2107         << Attrs << ExpectedFunctionOrMethod;
2108     return;
2109   }
2110 
2111   D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2112 }
2113 
2114 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2115   if (!S.getLangOpts().CFProtectionBranch)
2116     S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2117   else
2118     handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2119 }
2120 
2121 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2122   if (!checkAttributeNumArgs(*this, Attrs, 0)) {
2123     Attrs.setInvalid();
2124     return true;
2125   }
2126 
2127   return false;
2128 }
2129 
2130 bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2131   // Check whether the attribute is valid on the current target.
2132   if (!AL.existsInTarget(Context.getTargetInfo())) {
2133     Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2134         << AL << AL.getRange();
2135     AL.setInvalid();
2136     return true;
2137   }
2138 
2139   return false;
2140 }
2141 
2142 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2143 
2144   // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2145   // because 'analyzer_noreturn' does not impact the type.
2146   if (!isFunctionOrMethodOrBlock(D)) {
2147     ValueDecl *VD = dyn_cast<ValueDecl>(D);
2148     if (!VD || (!VD->getType()->isBlockPointerType() &&
2149                 !VD->getType()->isFunctionPointerType())) {
2150       S.Diag(AL.getLoc(), AL.isCXX11Attribute()
2151                               ? diag::err_attribute_wrong_decl_type
2152                               : diag::warn_attribute_wrong_decl_type)
2153           << AL << ExpectedFunctionMethodOrBlock;
2154       return;
2155     }
2156   }
2157 
2158   D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2159 }
2160 
2161 // PS3 PPU-specific.
2162 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2163   /*
2164     Returning a Vector Class in Registers
2165 
2166     According to the PPU ABI specifications, a class with a single member of
2167     vector type is returned in memory when used as the return value of a
2168     function.
2169     This results in inefficient code when implementing vector classes. To return
2170     the value in a single vector register, add the vecreturn attribute to the
2171     class definition. This attribute is also applicable to struct types.
2172 
2173     Example:
2174 
2175     struct Vector
2176     {
2177       __vector float xyzw;
2178     } __attribute__((vecreturn));
2179 
2180     Vector Add(Vector lhs, Vector rhs)
2181     {
2182       Vector result;
2183       result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2184       return result; // This will be returned in a register
2185     }
2186   */
2187   if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2188     S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2189     return;
2190   }
2191 
2192   const auto *R = cast<RecordDecl>(D);
2193   int count = 0;
2194 
2195   if (!isa<CXXRecordDecl>(R)) {
2196     S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2197     return;
2198   }
2199 
2200   if (!cast<CXXRecordDecl>(R)->isPOD()) {
2201     S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2202     return;
2203   }
2204 
2205   for (const auto *I : R->fields()) {
2206     if ((count == 1) || !I->getType()->isVectorType()) {
2207       S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2208       return;
2209     }
2210     count++;
2211   }
2212 
2213   D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2214 }
2215 
2216 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2217                                  const ParsedAttr &AL) {
2218   if (isa<ParmVarDecl>(D)) {
2219     // [[carries_dependency]] can only be applied to a parameter if it is a
2220     // parameter of a function declaration or lambda.
2221     if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2222       S.Diag(AL.getLoc(),
2223              diag::err_carries_dependency_param_not_function_decl);
2224       return;
2225     }
2226   }
2227 
2228   D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2229 }
2230 
2231 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2232   bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2233 
2234   // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2235   // about using it as an extension.
2236   if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2237     S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2238 
2239   D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2240 }
2241 
2242 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2243   uint32_t priority = ConstructorAttr::DefaultPriority;
2244   if (AL.getNumArgs() &&
2245       !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2246     return;
2247 
2248   D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2249 }
2250 
2251 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2252   uint32_t priority = DestructorAttr::DefaultPriority;
2253   if (AL.getNumArgs() &&
2254       !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2255     return;
2256 
2257   D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2258 }
2259 
2260 template <typename AttrTy>
2261 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2262   // Handle the case where the attribute has a text message.
2263   StringRef Str;
2264   if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2265     return;
2266 
2267   D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2268 }
2269 
2270 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2271                                           const ParsedAttr &AL) {
2272   if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2273     S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2274         << AL << AL.getRange();
2275     return;
2276   }
2277 
2278   D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2279 }
2280 
2281 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2282                                   IdentifierInfo *Platform,
2283                                   VersionTuple Introduced,
2284                                   VersionTuple Deprecated,
2285                                   VersionTuple Obsoleted) {
2286   StringRef PlatformName
2287     = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2288   if (PlatformName.empty())
2289     PlatformName = Platform->getName();
2290 
2291   // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2292   // of these steps are needed).
2293   if (!Introduced.empty() && !Deprecated.empty() &&
2294       !(Introduced <= Deprecated)) {
2295     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2296       << 1 << PlatformName << Deprecated.getAsString()
2297       << 0 << Introduced.getAsString();
2298     return true;
2299   }
2300 
2301   if (!Introduced.empty() && !Obsoleted.empty() &&
2302       !(Introduced <= Obsoleted)) {
2303     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2304       << 2 << PlatformName << Obsoleted.getAsString()
2305       << 0 << Introduced.getAsString();
2306     return true;
2307   }
2308 
2309   if (!Deprecated.empty() && !Obsoleted.empty() &&
2310       !(Deprecated <= Obsoleted)) {
2311     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2312       << 2 << PlatformName << Obsoleted.getAsString()
2313       << 1 << Deprecated.getAsString();
2314     return true;
2315   }
2316 
2317   return false;
2318 }
2319 
2320 /// Check whether the two versions match.
2321 ///
2322 /// If either version tuple is empty, then they are assumed to match. If
2323 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2324 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2325                           bool BeforeIsOkay) {
2326   if (X.empty() || Y.empty())
2327     return true;
2328 
2329   if (X == Y)
2330     return true;
2331 
2332   if (BeforeIsOkay && X < Y)
2333     return true;
2334 
2335   return false;
2336 }
2337 
2338 AvailabilityAttr *Sema::mergeAvailabilityAttr(
2339     NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2340     bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2341     VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2342     bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2343     int Priority) {
2344   VersionTuple MergedIntroduced = Introduced;
2345   VersionTuple MergedDeprecated = Deprecated;
2346   VersionTuple MergedObsoleted = Obsoleted;
2347   bool FoundAny = false;
2348   bool OverrideOrImpl = false;
2349   switch (AMK) {
2350   case AMK_None:
2351   case AMK_Redeclaration:
2352     OverrideOrImpl = false;
2353     break;
2354 
2355   case AMK_Override:
2356   case AMK_ProtocolImplementation:
2357     OverrideOrImpl = true;
2358     break;
2359   }
2360 
2361   if (D->hasAttrs()) {
2362     AttrVec &Attrs = D->getAttrs();
2363     for (unsigned i = 0, e = Attrs.size(); i != e;) {
2364       const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2365       if (!OldAA) {
2366         ++i;
2367         continue;
2368       }
2369 
2370       IdentifierInfo *OldPlatform = OldAA->getPlatform();
2371       if (OldPlatform != Platform) {
2372         ++i;
2373         continue;
2374       }
2375 
2376       // If there is an existing availability attribute for this platform that
2377       // has a lower priority use the existing one and discard the new
2378       // attribute.
2379       if (OldAA->getPriority() < Priority)
2380         return nullptr;
2381 
2382       // If there is an existing attribute for this platform that has a higher
2383       // priority than the new attribute then erase the old one and continue
2384       // processing the attributes.
2385       if (OldAA->getPriority() > Priority) {
2386         Attrs.erase(Attrs.begin() + i);
2387         --e;
2388         continue;
2389       }
2390 
2391       FoundAny = true;
2392       VersionTuple OldIntroduced = OldAA->getIntroduced();
2393       VersionTuple OldDeprecated = OldAA->getDeprecated();
2394       VersionTuple OldObsoleted = OldAA->getObsoleted();
2395       bool OldIsUnavailable = OldAA->getUnavailable();
2396 
2397       if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2398           !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2399           !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2400           !(OldIsUnavailable == IsUnavailable ||
2401             (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2402         if (OverrideOrImpl) {
2403           int Which = -1;
2404           VersionTuple FirstVersion;
2405           VersionTuple SecondVersion;
2406           if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2407             Which = 0;
2408             FirstVersion = OldIntroduced;
2409             SecondVersion = Introduced;
2410           } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2411             Which = 1;
2412             FirstVersion = Deprecated;
2413             SecondVersion = OldDeprecated;
2414           } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2415             Which = 2;
2416             FirstVersion = Obsoleted;
2417             SecondVersion = OldObsoleted;
2418           }
2419 
2420           if (Which == -1) {
2421             Diag(OldAA->getLocation(),
2422                  diag::warn_mismatched_availability_override_unavail)
2423               << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2424               << (AMK == AMK_Override);
2425           } else {
2426             Diag(OldAA->getLocation(),
2427                  diag::warn_mismatched_availability_override)
2428               << Which
2429               << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2430               << FirstVersion.getAsString() << SecondVersion.getAsString()
2431               << (AMK == AMK_Override);
2432           }
2433           if (AMK == AMK_Override)
2434             Diag(CI.getLoc(), diag::note_overridden_method);
2435           else
2436             Diag(CI.getLoc(), diag::note_protocol_method);
2437         } else {
2438           Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2439           Diag(CI.getLoc(), diag::note_previous_attribute);
2440         }
2441 
2442         Attrs.erase(Attrs.begin() + i);
2443         --e;
2444         continue;
2445       }
2446 
2447       VersionTuple MergedIntroduced2 = MergedIntroduced;
2448       VersionTuple MergedDeprecated2 = MergedDeprecated;
2449       VersionTuple MergedObsoleted2 = MergedObsoleted;
2450 
2451       if (MergedIntroduced2.empty())
2452         MergedIntroduced2 = OldIntroduced;
2453       if (MergedDeprecated2.empty())
2454         MergedDeprecated2 = OldDeprecated;
2455       if (MergedObsoleted2.empty())
2456         MergedObsoleted2 = OldObsoleted;
2457 
2458       if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2459                                 MergedIntroduced2, MergedDeprecated2,
2460                                 MergedObsoleted2)) {
2461         Attrs.erase(Attrs.begin() + i);
2462         --e;
2463         continue;
2464       }
2465 
2466       MergedIntroduced = MergedIntroduced2;
2467       MergedDeprecated = MergedDeprecated2;
2468       MergedObsoleted = MergedObsoleted2;
2469       ++i;
2470     }
2471   }
2472 
2473   if (FoundAny &&
2474       MergedIntroduced == Introduced &&
2475       MergedDeprecated == Deprecated &&
2476       MergedObsoleted == Obsoleted)
2477     return nullptr;
2478 
2479   // Only create a new attribute if !OverrideOrImpl, but we want to do
2480   // the checking.
2481   if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2482                              MergedDeprecated, MergedObsoleted) &&
2483       !OverrideOrImpl) {
2484     auto *Avail = ::new (Context) AvailabilityAttr(
2485         Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2486         Message, IsStrict, Replacement, Priority);
2487     Avail->setImplicit(Implicit);
2488     return Avail;
2489   }
2490   return nullptr;
2491 }
2492 
2493 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2494   if (!checkAttributeNumArgs(S, AL, 1))
2495     return;
2496   IdentifierLoc *Platform = AL.getArgAsIdent(0);
2497 
2498   IdentifierInfo *II = Platform->Ident;
2499   if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2500     S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2501       << Platform->Ident;
2502 
2503   auto *ND = dyn_cast<NamedDecl>(D);
2504   if (!ND) // We warned about this already, so just return.
2505     return;
2506 
2507   AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2508   AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2509   AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2510   bool IsUnavailable = AL.getUnavailableLoc().isValid();
2511   bool IsStrict = AL.getStrictLoc().isValid();
2512   StringRef Str;
2513   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2514     Str = SE->getString();
2515   StringRef Replacement;
2516   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2517     Replacement = SE->getString();
2518 
2519   if (II->isStr("swift")) {
2520     if (Introduced.isValid() || Obsoleted.isValid() ||
2521         (!IsUnavailable && !Deprecated.isValid())) {
2522       S.Diag(AL.getLoc(),
2523              diag::warn_availability_swift_unavailable_deprecated_only);
2524       return;
2525     }
2526   }
2527 
2528   int PriorityModifier = AL.isPragmaClangAttribute()
2529                              ? Sema::AP_PragmaClangAttribute
2530                              : Sema::AP_Explicit;
2531   AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2532       ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2533       Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2534       Sema::AMK_None, PriorityModifier);
2535   if (NewAttr)
2536     D->addAttr(NewAttr);
2537 
2538   // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2539   // matches before the start of the watchOS platform.
2540   if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2541     IdentifierInfo *NewII = nullptr;
2542     if (II->getName() == "ios")
2543       NewII = &S.Context.Idents.get("watchos");
2544     else if (II->getName() == "ios_app_extension")
2545       NewII = &S.Context.Idents.get("watchos_app_extension");
2546 
2547     if (NewII) {
2548         auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2549           if (Version.empty())
2550             return Version;
2551           auto Major = Version.getMajor();
2552           auto NewMajor = Major >= 9 ? Major - 7 : 0;
2553           if (NewMajor >= 2) {
2554             if (Version.getMinor().hasValue()) {
2555               if (Version.getSubminor().hasValue())
2556                 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2557                                     Version.getSubminor().getValue());
2558               else
2559                 return VersionTuple(NewMajor, Version.getMinor().getValue());
2560             }
2561             return VersionTuple(NewMajor);
2562           }
2563 
2564           return VersionTuple(2, 0);
2565         };
2566 
2567         auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2568         auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2569         auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2570 
2571         AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2572             ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2573             NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2574             Sema::AMK_None,
2575             PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2576         if (NewAttr)
2577           D->addAttr(NewAttr);
2578       }
2579   } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2580     // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2581     // matches before the start of the tvOS platform.
2582     IdentifierInfo *NewII = nullptr;
2583     if (II->getName() == "ios")
2584       NewII = &S.Context.Idents.get("tvos");
2585     else if (II->getName() == "ios_app_extension")
2586       NewII = &S.Context.Idents.get("tvos_app_extension");
2587 
2588     if (NewII) {
2589       AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2590           ND, AL, NewII, true /*Implicit*/, Introduced.Version,
2591           Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2592           Replacement, Sema::AMK_None,
2593           PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2594       if (NewAttr)
2595         D->addAttr(NewAttr);
2596       }
2597   }
2598 }
2599 
2600 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2601                                            const ParsedAttr &AL) {
2602   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2603     return;
2604   assert(checkAttributeAtMostNumArgs(S, AL, 3) &&
2605          "Invalid number of arguments in an external_source_symbol attribute");
2606 
2607   StringRef Language;
2608   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2609     Language = SE->getString();
2610   StringRef DefinedIn;
2611   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2612     DefinedIn = SE->getString();
2613   bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2614 
2615   D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2616       S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration));
2617 }
2618 
2619 template <class T>
2620 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2621                               typename T::VisibilityType value) {
2622   T *existingAttr = D->getAttr<T>();
2623   if (existingAttr) {
2624     typename T::VisibilityType existingValue = existingAttr->getVisibility();
2625     if (existingValue == value)
2626       return nullptr;
2627     S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2628     S.Diag(CI.getLoc(), diag::note_previous_attribute);
2629     D->dropAttr<T>();
2630   }
2631   return ::new (S.Context) T(S.Context, CI, value);
2632 }
2633 
2634 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2635                                           const AttributeCommonInfo &CI,
2636                                           VisibilityAttr::VisibilityType Vis) {
2637   return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2638 }
2639 
2640 TypeVisibilityAttr *
2641 Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2642                               TypeVisibilityAttr::VisibilityType Vis) {
2643   return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2644 }
2645 
2646 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2647                                  bool isTypeVisibility) {
2648   // Visibility attributes don't mean anything on a typedef.
2649   if (isa<TypedefNameDecl>(D)) {
2650     S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2651     return;
2652   }
2653 
2654   // 'type_visibility' can only go on a type or namespace.
2655   if (isTypeVisibility &&
2656       !(isa<TagDecl>(D) ||
2657         isa<ObjCInterfaceDecl>(D) ||
2658         isa<NamespaceDecl>(D))) {
2659     S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2660         << AL << ExpectedTypeOrNamespace;
2661     return;
2662   }
2663 
2664   // Check that the argument is a string literal.
2665   StringRef TypeStr;
2666   SourceLocation LiteralLoc;
2667   if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2668     return;
2669 
2670   VisibilityAttr::VisibilityType type;
2671   if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2672     S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2673                                                                 << TypeStr;
2674     return;
2675   }
2676 
2677   // Complain about attempts to use protected visibility on targets
2678   // (like Darwin) that don't support it.
2679   if (type == VisibilityAttr::Protected &&
2680       !S.Context.getTargetInfo().hasProtectedVisibility()) {
2681     S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2682     type = VisibilityAttr::Default;
2683   }
2684 
2685   Attr *newAttr;
2686   if (isTypeVisibility) {
2687     newAttr = S.mergeTypeVisibilityAttr(
2688         D, AL, (TypeVisibilityAttr::VisibilityType)type);
2689   } else {
2690     newAttr = S.mergeVisibilityAttr(D, AL, type);
2691   }
2692   if (newAttr)
2693     D->addAttr(newAttr);
2694 }
2695 
2696 static void handleObjCNonRuntimeProtocolAttr(Sema &S, Decl *D,
2697                                              const ParsedAttr &AL) {
2698   handleSimpleAttribute<ObjCNonRuntimeProtocolAttr>(S, D, AL);
2699 }
2700 
2701 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2702   // objc_direct cannot be set on methods declared in the context of a protocol
2703   if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
2704     S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2705     return;
2706   }
2707 
2708   if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2709     handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2710   } else {
2711     S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2712   }
2713 }
2714 
2715 static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
2716                                         const ParsedAttr &AL) {
2717   if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2718     handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2719   } else {
2720     S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2721   }
2722 }
2723 
2724 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2725   const auto *M = cast<ObjCMethodDecl>(D);
2726   if (!AL.isArgIdent(0)) {
2727     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2728         << AL << 1 << AANT_ArgumentIdentifier;
2729     return;
2730   }
2731 
2732   IdentifierLoc *IL = AL.getArgAsIdent(0);
2733   ObjCMethodFamilyAttr::FamilyKind F;
2734   if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2735     S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2736     return;
2737   }
2738 
2739   if (F == ObjCMethodFamilyAttr::OMF_init &&
2740       !M->getReturnType()->isObjCObjectPointerType()) {
2741     S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2742         << M->getReturnType();
2743     // Ignore the attribute.
2744     return;
2745   }
2746 
2747   D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
2748 }
2749 
2750 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2751   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2752     QualType T = TD->getUnderlyingType();
2753     if (!T->isCARCBridgableType()) {
2754       S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2755       return;
2756     }
2757   }
2758   else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2759     QualType T = PD->getType();
2760     if (!T->isCARCBridgableType()) {
2761       S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2762       return;
2763     }
2764   }
2765   else {
2766     // It is okay to include this attribute on properties, e.g.:
2767     //
2768     //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2769     //
2770     // In this case it follows tradition and suppresses an error in the above
2771     // case.
2772     S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2773   }
2774   D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
2775 }
2776 
2777 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2778   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2779     QualType T = TD->getUnderlyingType();
2780     if (!T->isObjCObjectPointerType()) {
2781       S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2782       return;
2783     }
2784   } else {
2785     S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2786     return;
2787   }
2788   D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
2789 }
2790 
2791 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2792   if (!AL.isArgIdent(0)) {
2793     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2794         << AL << 1 << AANT_ArgumentIdentifier;
2795     return;
2796   }
2797 
2798   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2799   BlocksAttr::BlockType type;
2800   if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2801     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2802     return;
2803   }
2804 
2805   D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
2806 }
2807 
2808 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2809   unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2810   if (AL.getNumArgs() > 0) {
2811     Expr *E = AL.getArgAsExpr(0);
2812     Optional<llvm::APSInt> Idx = llvm::APSInt(32);
2813     if (E->isTypeDependent() || E->isValueDependent() ||
2814         !(Idx = E->getIntegerConstantExpr(S.Context))) {
2815       S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2816           << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2817       return;
2818     }
2819 
2820     if (Idx->isSigned() && Idx->isNegative()) {
2821       S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2822         << E->getSourceRange();
2823       return;
2824     }
2825 
2826     sentinel = Idx->getZExtValue();
2827   }
2828 
2829   unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2830   if (AL.getNumArgs() > 1) {
2831     Expr *E = AL.getArgAsExpr(1);
2832     Optional<llvm::APSInt> Idx = llvm::APSInt(32);
2833     if (E->isTypeDependent() || E->isValueDependent() ||
2834         !(Idx = E->getIntegerConstantExpr(S.Context))) {
2835       S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2836           << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2837       return;
2838     }
2839     nullPos = Idx->getZExtValue();
2840 
2841     if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
2842       // FIXME: This error message could be improved, it would be nice
2843       // to say what the bounds actually are.
2844       S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2845         << E->getSourceRange();
2846       return;
2847     }
2848   }
2849 
2850   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2851     const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2852     if (isa<FunctionNoProtoType>(FT)) {
2853       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2854       return;
2855     }
2856 
2857     if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2858       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2859       return;
2860     }
2861   } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2862     if (!MD->isVariadic()) {
2863       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2864       return;
2865     }
2866   } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2867     if (!BD->isVariadic()) {
2868       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2869       return;
2870     }
2871   } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2872     QualType Ty = V->getType();
2873     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2874       const FunctionType *FT = Ty->isFunctionPointerType()
2875        ? D->getFunctionType()
2876        : Ty->castAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2877       if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2878         int m = Ty->isFunctionPointerType() ? 0 : 1;
2879         S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2880         return;
2881       }
2882     } else {
2883       S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2884           << AL << ExpectedFunctionMethodOrBlock;
2885       return;
2886     }
2887   } else {
2888     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2889         << AL << ExpectedFunctionMethodOrBlock;
2890     return;
2891   }
2892   D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
2893 }
2894 
2895 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2896   if (D->getFunctionType() &&
2897       D->getFunctionType()->getReturnType()->isVoidType() &&
2898       !isa<CXXConstructorDecl>(D)) {
2899     S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2900     return;
2901   }
2902   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2903     if (MD->getReturnType()->isVoidType()) {
2904       S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2905       return;
2906     }
2907 
2908   StringRef Str;
2909   if ((AL.isCXX11Attribute() || AL.isC2xAttribute()) && !AL.getScopeName()) {
2910     // The standard attribute cannot be applied to variable declarations such
2911     // as a function pointer.
2912     if (isa<VarDecl>(D))
2913       S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
2914           << AL << "functions, classes, or enumerations";
2915 
2916     // If this is spelled as the standard C++17 attribute, but not in C++17,
2917     // warn about using it as an extension. If there are attribute arguments,
2918     // then claim it's a C++2a extension instead.
2919     // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2920     // extension warning for C2x mode.
2921     const LangOptions &LO = S.getLangOpts();
2922     if (AL.getNumArgs() == 1) {
2923       if (LO.CPlusPlus && !LO.CPlusPlus20)
2924         S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
2925 
2926       // Since this this is spelled [[nodiscard]], get the optional string
2927       // literal. If in C++ mode, but not in C++2a mode, diagnose as an
2928       // extension.
2929       // FIXME: C2x should support this feature as well, even as an extension.
2930       if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2931         return;
2932     } else if (LO.CPlusPlus && !LO.CPlusPlus17)
2933       S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2934   }
2935 
2936   D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
2937 }
2938 
2939 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2940   // weak_import only applies to variable & function declarations.
2941   bool isDef = false;
2942   if (!D->canBeWeakImported(isDef)) {
2943     if (isDef)
2944       S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2945         << "weak_import";
2946     else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2947              (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2948               (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2949       // Nothing to warn about here.
2950     } else
2951       S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2952           << AL << ExpectedVariableOrFunction;
2953 
2954     return;
2955   }
2956 
2957   D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
2958 }
2959 
2960 // Handles reqd_work_group_size and work_group_size_hint.
2961 template <typename WorkGroupAttr>
2962 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2963   uint32_t WGSize[3];
2964   for (unsigned i = 0; i < 3; ++i) {
2965     const Expr *E = AL.getArgAsExpr(i);
2966     if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
2967                              /*StrictlyUnsigned=*/true))
2968       return;
2969     if (WGSize[i] == 0) {
2970       S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2971           << AL << E->getSourceRange();
2972       return;
2973     }
2974   }
2975 
2976   WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2977   if (Existing && !(Existing->getXDim() == WGSize[0] &&
2978                     Existing->getYDim() == WGSize[1] &&
2979                     Existing->getZDim() == WGSize[2]))
2980     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2981 
2982   D->addAttr(::new (S.Context)
2983                  WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
2984 }
2985 
2986 // Handles intel_reqd_sub_group_size.
2987 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2988   uint32_t SGSize;
2989   const Expr *E = AL.getArgAsExpr(0);
2990   if (!checkUInt32Argument(S, AL, E, SGSize))
2991     return;
2992   if (SGSize == 0) {
2993     S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2994         << AL << E->getSourceRange();
2995     return;
2996   }
2997 
2998   OpenCLIntelReqdSubGroupSizeAttr *Existing =
2999       D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
3000   if (Existing && Existing->getSubGroupSize() != SGSize)
3001     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3002 
3003   D->addAttr(::new (S.Context)
3004                  OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
3005 }
3006 
3007 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3008   if (!AL.hasParsedType()) {
3009     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3010     return;
3011   }
3012 
3013   TypeSourceInfo *ParmTSI = nullptr;
3014   QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
3015   assert(ParmTSI && "no type source info for attribute argument");
3016 
3017   if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
3018       (ParmType->isBooleanType() ||
3019        !ParmType->isIntegralType(S.getASTContext()))) {
3020     S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
3021     return;
3022   }
3023 
3024   if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
3025     if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
3026       S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3027       return;
3028     }
3029   }
3030 
3031   D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
3032 }
3033 
3034 SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3035                                     StringRef Name) {
3036   // Explicit or partial specializations do not inherit
3037   // the section attribute from the primary template.
3038   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3039     if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
3040         FD->isFunctionTemplateSpecialization())
3041       return nullptr;
3042   }
3043   if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3044     if (ExistingAttr->getName() == Name)
3045       return nullptr;
3046     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3047          << 1 /*section*/;
3048     Diag(CI.getLoc(), diag::note_previous_attribute);
3049     return nullptr;
3050   }
3051   return ::new (Context) SectionAttr(Context, CI, Name);
3052 }
3053 
3054 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3055   std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
3056   if (!Error.empty()) {
3057     Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
3058          << 1 /*'section'*/;
3059     return false;
3060   }
3061   return true;
3062 }
3063 
3064 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3065   // Make sure that there is a string literal as the sections's single
3066   // argument.
3067   StringRef Str;
3068   SourceLocation LiteralLoc;
3069   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3070     return;
3071 
3072   if (!S.checkSectionName(LiteralLoc, Str))
3073     return;
3074 
3075   // If the target wants to validate the section specifier, make it happen.
3076   std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
3077   if (!Error.empty()) {
3078     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3079     << Error;
3080     return;
3081   }
3082 
3083   SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
3084   if (NewAttr) {
3085     D->addAttr(NewAttr);
3086     if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl,
3087             ObjCPropertyDecl>(D))
3088       S.UnifySection(NewAttr->getName(),
3089                      ASTContext::PSF_Execute | ASTContext::PSF_Read,
3090                      cast<NamedDecl>(D));
3091   }
3092 }
3093 
3094 // This is used for `__declspec(code_seg("segname"))` on a decl.
3095 // `#pragma code_seg("segname")` uses checkSectionName() instead.
3096 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3097                              StringRef CodeSegName) {
3098   std::string Error =
3099       S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
3100   if (!Error.empty()) {
3101     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3102         << Error << 0 /*'code-seg'*/;
3103     return false;
3104   }
3105 
3106   return true;
3107 }
3108 
3109 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3110                                     StringRef Name) {
3111   // Explicit or partial specializations do not inherit
3112   // the code_seg attribute from the primary template.
3113   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3114     if (FD->isFunctionTemplateSpecialization())
3115       return nullptr;
3116   }
3117   if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3118     if (ExistingAttr->getName() == Name)
3119       return nullptr;
3120     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3121          << 0 /*codeseg*/;
3122     Diag(CI.getLoc(), diag::note_previous_attribute);
3123     return nullptr;
3124   }
3125   return ::new (Context) CodeSegAttr(Context, CI, Name);
3126 }
3127 
3128 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3129   StringRef Str;
3130   SourceLocation LiteralLoc;
3131   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3132     return;
3133   if (!checkCodeSegName(S, LiteralLoc, Str))
3134     return;
3135   if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3136     if (!ExistingAttr->isImplicit()) {
3137       S.Diag(AL.getLoc(),
3138              ExistingAttr->getName() == Str
3139              ? diag::warn_duplicate_codeseg_attribute
3140              : diag::err_conflicting_codeseg_attribute);
3141       return;
3142     }
3143     D->dropAttr<CodeSegAttr>();
3144   }
3145   if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3146     D->addAttr(CSA);
3147 }
3148 
3149 // Check for things we'd like to warn about. Multiversioning issues are
3150 // handled later in the process, once we know how many exist.
3151 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3152   enum FirstParam { Unsupported, Duplicate, Unknown };
3153   enum SecondParam { None, Architecture, Tune };
3154   if (AttrStr.find("fpmath=") != StringRef::npos)
3155     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3156            << Unsupported << None << "fpmath=";
3157 
3158   // Diagnose use of tune if target doesn't support it.
3159   if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
3160       AttrStr.find("tune=") != StringRef::npos)
3161     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3162            << Unsupported << None << "tune=";
3163 
3164   ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3165 
3166   if (!ParsedAttrs.Architecture.empty() &&
3167       !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3168     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3169            << Unknown << Architecture << ParsedAttrs.Architecture;
3170 
3171   if (!ParsedAttrs.Tune.empty() &&
3172       !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
3173     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3174            << Unknown << Tune << ParsedAttrs.Tune;
3175 
3176   if (ParsedAttrs.DuplicateArchitecture)
3177     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3178            << Duplicate << None << "arch=";
3179   if (ParsedAttrs.DuplicateTune)
3180     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3181            << Duplicate << None << "tune=";
3182 
3183   for (const auto &Feature : ParsedAttrs.Features) {
3184     auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3185     if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3186       return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3187              << Unsupported << None << CurFeature;
3188   }
3189 
3190   TargetInfo::BranchProtectionInfo BPI;
3191   StringRef Error;
3192   if (!ParsedAttrs.BranchProtection.empty() &&
3193       !Context.getTargetInfo().validateBranchProtection(
3194           ParsedAttrs.BranchProtection, BPI, Error)) {
3195     if (Error.empty())
3196       return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3197              << Unsupported << None << "branch-protection";
3198     else
3199       return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3200              << Error;
3201   }
3202 
3203   return false;
3204 }
3205 
3206 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3207   StringRef Str;
3208   SourceLocation LiteralLoc;
3209   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3210       S.checkTargetAttr(LiteralLoc, Str))
3211     return;
3212 
3213   TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3214   D->addAttr(NewAttr);
3215 }
3216 
3217 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3218   Expr *E = AL.getArgAsExpr(0);
3219   uint32_t VecWidth;
3220   if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3221     AL.setInvalid();
3222     return;
3223   }
3224 
3225   MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3226   if (Existing && Existing->getVectorWidth() != VecWidth) {
3227     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3228     return;
3229   }
3230 
3231   D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3232 }
3233 
3234 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3235   Expr *E = AL.getArgAsExpr(0);
3236   SourceLocation Loc = E->getExprLoc();
3237   FunctionDecl *FD = nullptr;
3238   DeclarationNameInfo NI;
3239 
3240   // gcc only allows for simple identifiers. Since we support more than gcc, we
3241   // will warn the user.
3242   if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3243     if (DRE->hasQualifier())
3244       S.Diag(Loc, diag::warn_cleanup_ext);
3245     FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3246     NI = DRE->getNameInfo();
3247     if (!FD) {
3248       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3249         << NI.getName();
3250       return;
3251     }
3252   } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3253     if (ULE->hasExplicitTemplateArgs())
3254       S.Diag(Loc, diag::warn_cleanup_ext);
3255     FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3256     NI = ULE->getNameInfo();
3257     if (!FD) {
3258       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3259         << NI.getName();
3260       if (ULE->getType() == S.Context.OverloadTy)
3261         S.NoteAllOverloadCandidates(ULE);
3262       return;
3263     }
3264   } else {
3265     S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3266     return;
3267   }
3268 
3269   if (FD->getNumParams() != 1) {
3270     S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3271       << NI.getName();
3272     return;
3273   }
3274 
3275   // We're currently more strict than GCC about what function types we accept.
3276   // If this ever proves to be a problem it should be easy to fix.
3277   QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3278   QualType ParamTy = FD->getParamDecl(0)->getType();
3279   if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3280                                    ParamTy, Ty) != Sema::Compatible) {
3281     S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3282       << NI.getName() << ParamTy << Ty;
3283     return;
3284   }
3285 
3286   D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3287 }
3288 
3289 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3290                                         const ParsedAttr &AL) {
3291   if (!AL.isArgIdent(0)) {
3292     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3293         << AL << 0 << AANT_ArgumentIdentifier;
3294     return;
3295   }
3296 
3297   EnumExtensibilityAttr::Kind ExtensibilityKind;
3298   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3299   if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3300                                                ExtensibilityKind)) {
3301     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3302     return;
3303   }
3304 
3305   D->addAttr(::new (S.Context)
3306                  EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3307 }
3308 
3309 /// Handle __attribute__((format_arg((idx)))) attribute based on
3310 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3311 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3312   Expr *IdxExpr = AL.getArgAsExpr(0);
3313   ParamIdx Idx;
3314   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3315     return;
3316 
3317   // Make sure the format string is really a string.
3318   QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3319 
3320   bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3321   if (NotNSStringTy &&
3322       !isCFStringType(Ty, S.Context) &&
3323       (!Ty->isPointerType() ||
3324        !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3325     S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3326         << "a string type" << IdxExpr->getSourceRange()
3327         << getFunctionOrMethodParamRange(D, 0);
3328     return;
3329   }
3330   Ty = getFunctionOrMethodResultType(D);
3331   if (!isNSStringType(Ty, S.Context) &&
3332       !isCFStringType(Ty, S.Context) &&
3333       (!Ty->isPointerType() ||
3334        !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3335     S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3336         << (NotNSStringTy ? "string type" : "NSString")
3337         << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3338     return;
3339   }
3340 
3341   D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3342 }
3343 
3344 enum FormatAttrKind {
3345   CFStringFormat,
3346   NSStringFormat,
3347   StrftimeFormat,
3348   SupportedFormat,
3349   IgnoredFormat,
3350   InvalidFormat
3351 };
3352 
3353 /// getFormatAttrKind - Map from format attribute names to supported format
3354 /// types.
3355 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3356   return llvm::StringSwitch<FormatAttrKind>(Format)
3357       // Check for formats that get handled specially.
3358       .Case("NSString", NSStringFormat)
3359       .Case("CFString", CFStringFormat)
3360       .Case("strftime", StrftimeFormat)
3361 
3362       // Otherwise, check for supported formats.
3363       .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3364       .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3365       .Case("kprintf", SupportedFormat)         // OpenBSD.
3366       .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3367       .Case("os_trace", SupportedFormat)
3368       .Case("os_log", SupportedFormat)
3369 
3370       .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3371       .Default(InvalidFormat);
3372 }
3373 
3374 /// Handle __attribute__((init_priority(priority))) attributes based on
3375 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3376 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3377   if (!S.getLangOpts().CPlusPlus) {
3378     S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3379     return;
3380   }
3381 
3382   if (S.getCurFunctionOrMethodDecl()) {
3383     S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3384     AL.setInvalid();
3385     return;
3386   }
3387   QualType T = cast<VarDecl>(D)->getType();
3388   if (S.Context.getAsArrayType(T))
3389     T = S.Context.getBaseElementType(T);
3390   if (!T->getAs<RecordType>()) {
3391     S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3392     AL.setInvalid();
3393     return;
3394   }
3395 
3396   Expr *E = AL.getArgAsExpr(0);
3397   uint32_t prioritynum;
3398   if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3399     AL.setInvalid();
3400     return;
3401   }
3402 
3403   // Only perform the priority check if the attribute is outside of a system
3404   // header. Values <= 100 are reserved for the implementation, and libc++
3405   // benefits from being able to specify values in that range.
3406   if ((prioritynum < 101 || prioritynum > 65535) &&
3407       !S.getSourceManager().isInSystemHeader(AL.getLoc())) {
3408     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3409         << E->getSourceRange() << AL << 101 << 65535;
3410     AL.setInvalid();
3411     return;
3412   }
3413   D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3414 }
3415 
3416 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3417                                   IdentifierInfo *Format, int FormatIdx,
3418                                   int FirstArg) {
3419   // Check whether we already have an equivalent format attribute.
3420   for (auto *F : D->specific_attrs<FormatAttr>()) {
3421     if (F->getType() == Format &&
3422         F->getFormatIdx() == FormatIdx &&
3423         F->getFirstArg() == FirstArg) {
3424       // If we don't have a valid location for this attribute, adopt the
3425       // location.
3426       if (F->getLocation().isInvalid())
3427         F->setRange(CI.getRange());
3428       return nullptr;
3429     }
3430   }
3431 
3432   return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3433 }
3434 
3435 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3436 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3437 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3438   if (!AL.isArgIdent(0)) {
3439     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3440         << AL << 1 << AANT_ArgumentIdentifier;
3441     return;
3442   }
3443 
3444   // In C++ the implicit 'this' function parameter also counts, and they are
3445   // counted from one.
3446   bool HasImplicitThisParam = isInstanceMethod(D);
3447   unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3448 
3449   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3450   StringRef Format = II->getName();
3451 
3452   if (normalizeName(Format)) {
3453     // If we've modified the string name, we need a new identifier for it.
3454     II = &S.Context.Idents.get(Format);
3455   }
3456 
3457   // Check for supported formats.
3458   FormatAttrKind Kind = getFormatAttrKind(Format);
3459 
3460   if (Kind == IgnoredFormat)
3461     return;
3462 
3463   if (Kind == InvalidFormat) {
3464     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3465         << AL << II->getName();
3466     return;
3467   }
3468 
3469   // checks for the 2nd argument
3470   Expr *IdxExpr = AL.getArgAsExpr(1);
3471   uint32_t Idx;
3472   if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3473     return;
3474 
3475   if (Idx < 1 || Idx > NumArgs) {
3476     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3477         << AL << 2 << IdxExpr->getSourceRange();
3478     return;
3479   }
3480 
3481   // FIXME: Do we need to bounds check?
3482   unsigned ArgIdx = Idx - 1;
3483 
3484   if (HasImplicitThisParam) {
3485     if (ArgIdx == 0) {
3486       S.Diag(AL.getLoc(),
3487              diag::err_format_attribute_implicit_this_format_string)
3488         << IdxExpr->getSourceRange();
3489       return;
3490     }
3491     ArgIdx--;
3492   }
3493 
3494   // make sure the format string is really a string
3495   QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3496 
3497   if (Kind == CFStringFormat) {
3498     if (!isCFStringType(Ty, S.Context)) {
3499       S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3500         << "a CFString" << IdxExpr->getSourceRange()
3501         << getFunctionOrMethodParamRange(D, ArgIdx);
3502       return;
3503     }
3504   } else if (Kind == NSStringFormat) {
3505     // FIXME: do we need to check if the type is NSString*?  What are the
3506     // semantics?
3507     if (!isNSStringType(Ty, S.Context)) {
3508       S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3509         << "an NSString" << IdxExpr->getSourceRange()
3510         << getFunctionOrMethodParamRange(D, ArgIdx);
3511       return;
3512     }
3513   } else if (!Ty->isPointerType() ||
3514              !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) {
3515     S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3516       << "a string type" << IdxExpr->getSourceRange()
3517       << getFunctionOrMethodParamRange(D, ArgIdx);
3518     return;
3519   }
3520 
3521   // check the 3rd argument
3522   Expr *FirstArgExpr = AL.getArgAsExpr(2);
3523   uint32_t FirstArg;
3524   if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3525     return;
3526 
3527   // check if the function is variadic if the 3rd argument non-zero
3528   if (FirstArg != 0) {
3529     if (isFunctionOrMethodVariadic(D)) {
3530       ++NumArgs; // +1 for ...
3531     } else {
3532       S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3533       return;
3534     }
3535   }
3536 
3537   // strftime requires FirstArg to be 0 because it doesn't read from any
3538   // variable the input is just the current time + the format string.
3539   if (Kind == StrftimeFormat) {
3540     if (FirstArg != 0) {
3541       S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3542         << FirstArgExpr->getSourceRange();
3543       return;
3544     }
3545   // if 0 it disables parameter checking (to use with e.g. va_list)
3546   } else if (FirstArg != 0 && FirstArg != NumArgs) {
3547     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3548         << AL << 3 << FirstArgExpr->getSourceRange();
3549     return;
3550   }
3551 
3552   FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3553   if (NewAttr)
3554     D->addAttr(NewAttr);
3555 }
3556 
3557 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3558 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3559   // The index that identifies the callback callee is mandatory.
3560   if (AL.getNumArgs() == 0) {
3561     S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3562         << AL.getRange();
3563     return;
3564   }
3565 
3566   bool HasImplicitThisParam = isInstanceMethod(D);
3567   int32_t NumArgs = getFunctionOrMethodNumParams(D);
3568 
3569   FunctionDecl *FD = D->getAsFunction();
3570   assert(FD && "Expected a function declaration!");
3571 
3572   llvm::StringMap<int> NameIdxMapping;
3573   NameIdxMapping["__"] = -1;
3574 
3575   NameIdxMapping["this"] = 0;
3576 
3577   int Idx = 1;
3578   for (const ParmVarDecl *PVD : FD->parameters())
3579     NameIdxMapping[PVD->getName()] = Idx++;
3580 
3581   auto UnknownName = NameIdxMapping.end();
3582 
3583   SmallVector<int, 8> EncodingIndices;
3584   for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3585     SourceRange SR;
3586     int32_t ArgIdx;
3587 
3588     if (AL.isArgIdent(I)) {
3589       IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3590       auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3591       if (It == UnknownName) {
3592         S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3593             << IdLoc->Ident << IdLoc->Loc;
3594         return;
3595       }
3596 
3597       SR = SourceRange(IdLoc->Loc);
3598       ArgIdx = It->second;
3599     } else if (AL.isArgExpr(I)) {
3600       Expr *IdxExpr = AL.getArgAsExpr(I);
3601 
3602       // If the expression is not parseable as an int32_t we have a problem.
3603       if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3604                                false)) {
3605         S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3606             << AL << (I + 1) << IdxExpr->getSourceRange();
3607         return;
3608       }
3609 
3610       // Check oob, excluding the special values, 0 and -1.
3611       if (ArgIdx < -1 || ArgIdx > NumArgs) {
3612         S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3613             << AL << (I + 1) << IdxExpr->getSourceRange();
3614         return;
3615       }
3616 
3617       SR = IdxExpr->getSourceRange();
3618     } else {
3619       llvm_unreachable("Unexpected ParsedAttr argument type!");
3620     }
3621 
3622     if (ArgIdx == 0 && !HasImplicitThisParam) {
3623       S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3624           << (I + 1) << SR;
3625       return;
3626     }
3627 
3628     // Adjust for the case we do not have an implicit "this" parameter. In this
3629     // case we decrease all positive values by 1 to get LLVM argument indices.
3630     if (!HasImplicitThisParam && ArgIdx > 0)
3631       ArgIdx -= 1;
3632 
3633     EncodingIndices.push_back(ArgIdx);
3634   }
3635 
3636   int CalleeIdx = EncodingIndices.front();
3637   // Check if the callee index is proper, thus not "this" and not "unknown".
3638   // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3639   // is false and positive if "HasImplicitThisParam" is true.
3640   if (CalleeIdx < (int)HasImplicitThisParam) {
3641     S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3642         << AL.getRange();
3643     return;
3644   }
3645 
3646   // Get the callee type, note the index adjustment as the AST doesn't contain
3647   // the this type (which the callee cannot reference anyway!).
3648   const Type *CalleeType =
3649       getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3650           .getTypePtr();
3651   if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3652     S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3653         << AL.getRange();
3654     return;
3655   }
3656 
3657   const Type *CalleeFnType =
3658       CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
3659 
3660   // TODO: Check the type of the callee arguments.
3661 
3662   const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3663   if (!CalleeFnProtoType) {
3664     S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3665         << AL.getRange();
3666     return;
3667   }
3668 
3669   if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3670     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3671         << AL << (unsigned)(EncodingIndices.size() - 1);
3672     return;
3673   }
3674 
3675   if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3676     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3677         << AL << (unsigned)(EncodingIndices.size() - 1);
3678     return;
3679   }
3680 
3681   if (CalleeFnProtoType->isVariadic()) {
3682     S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3683     return;
3684   }
3685 
3686   // Do not allow multiple callback attributes.
3687   if (D->hasAttr<CallbackAttr>()) {
3688     S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3689     return;
3690   }
3691 
3692   D->addAttr(::new (S.Context) CallbackAttr(
3693       S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3694 }
3695 
3696 static bool isFunctionLike(const Type &T) {
3697   // Check for explicit function types.
3698   // 'called_once' is only supported in Objective-C and it has
3699   // function pointers and block pointers.
3700   return T.isFunctionPointerType() || T.isBlockPointerType();
3701 }
3702 
3703 /// Handle 'called_once' attribute.
3704 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3705   // 'called_once' only applies to parameters representing functions.
3706   QualType T = cast<ParmVarDecl>(D)->getType();
3707 
3708   if (!isFunctionLike(*T)) {
3709     S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
3710     return;
3711   }
3712 
3713   D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
3714 }
3715 
3716 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3717   // Try to find the underlying union declaration.
3718   RecordDecl *RD = nullptr;
3719   const auto *TD = dyn_cast<TypedefNameDecl>(D);
3720   if (TD && TD->getUnderlyingType()->isUnionType())
3721     RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3722   else
3723     RD = dyn_cast<RecordDecl>(D);
3724 
3725   if (!RD || !RD->isUnion()) {
3726     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3727                                                               << ExpectedUnion;
3728     return;
3729   }
3730 
3731   if (!RD->isCompleteDefinition()) {
3732     if (!RD->isBeingDefined())
3733       S.Diag(AL.getLoc(),
3734              diag::warn_transparent_union_attribute_not_definition);
3735     return;
3736   }
3737 
3738   RecordDecl::field_iterator Field = RD->field_begin(),
3739                           FieldEnd = RD->field_end();
3740   if (Field == FieldEnd) {
3741     S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3742     return;
3743   }
3744 
3745   FieldDecl *FirstField = *Field;
3746   QualType FirstType = FirstField->getType();
3747   if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3748     S.Diag(FirstField->getLocation(),
3749            diag::warn_transparent_union_attribute_floating)
3750       << FirstType->isVectorType() << FirstType;
3751     return;
3752   }
3753 
3754   if (FirstType->isIncompleteType())
3755     return;
3756   uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3757   uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3758   for (; Field != FieldEnd; ++Field) {
3759     QualType FieldType = Field->getType();
3760     if (FieldType->isIncompleteType())
3761       return;
3762     // FIXME: this isn't fully correct; we also need to test whether the
3763     // members of the union would all have the same calling convention as the
3764     // first member of the union. Checking just the size and alignment isn't
3765     // sufficient (consider structs passed on the stack instead of in registers
3766     // as an example).
3767     if (S.Context.getTypeSize(FieldType) != FirstSize ||
3768         S.Context.getTypeAlign(FieldType) > FirstAlign) {
3769       // Warn if we drop the attribute.
3770       bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3771       unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
3772                                   : S.Context.getTypeAlign(FieldType);
3773       S.Diag(Field->getLocation(),
3774              diag::warn_transparent_union_attribute_field_size_align)
3775           << isSize << *Field << FieldBits;
3776       unsigned FirstBits = isSize ? FirstSize : FirstAlign;
3777       S.Diag(FirstField->getLocation(),
3778              diag::note_transparent_union_first_field_size_align)
3779           << isSize << FirstBits;
3780       return;
3781     }
3782   }
3783 
3784   RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3785 }
3786 
3787 void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
3788                              StringRef Str, MutableArrayRef<Expr *> Args) {
3789   auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
3790   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
3791   for (unsigned Idx = 0; Idx < Attr->args_size(); Idx++) {
3792     Expr *&E = Attr->args_begin()[Idx];
3793     assert(E && "error are handled before");
3794     if (E->isValueDependent() || E->isTypeDependent())
3795       continue;
3796 
3797     if (E->getType()->isArrayType())
3798       E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
3799                             clang::CK_ArrayToPointerDecay)
3800               .get();
3801     if (E->getType()->isFunctionType())
3802       E = ImplicitCastExpr::Create(Context,
3803                                    Context.getPointerType(E->getType()),
3804                                    clang::CK_FunctionToPointerDecay, E, nullptr,
3805                                    VK_RValue, FPOptionsOverride());
3806     if (E->isLValue())
3807       E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(),
3808                                    clang::CK_LValueToRValue, E, nullptr,
3809                                    VK_RValue, FPOptionsOverride());
3810 
3811     Expr::EvalResult Eval;
3812     Notes.clear();
3813     Eval.Diag = &Notes;
3814 
3815     bool Result =
3816         E->EvaluateAsConstantExpr(Eval, Context);
3817 
3818     /// Result means the expression can be folded to a constant.
3819     /// Note.empty() means the expression is a valid constant expression in the
3820     /// current language mode.
3821     if (!Result || !Notes.empty()) {
3822       Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
3823           << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
3824       for (auto &Note : Notes)
3825         Diag(Note.first, Note.second);
3826       return;
3827     }
3828     assert(Eval.Val.hasValue());
3829     E = ConstantExpr::Create(Context, E, Eval.Val);
3830   }
3831   D->addAttr(Attr);
3832 }
3833 
3834 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3835   // Make sure that there is a string literal as the annotation's first
3836   // argument.
3837   StringRef Str;
3838   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3839     return;
3840 
3841   llvm::SmallVector<Expr *, 4> Args;
3842   Args.reserve(AL.getNumArgs() - 1);
3843   for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
3844     assert(!AL.isArgIdent(Idx));
3845     Args.push_back(AL.getArgAsExpr(Idx));
3846   }
3847 
3848   S.AddAnnotationAttr(D, AL, Str, Args);
3849 }
3850 
3851 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3852   S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3853 }
3854 
3855 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
3856   AlignValueAttr TmpAttr(Context, CI, E);
3857   SourceLocation AttrLoc = CI.getLoc();
3858 
3859   QualType T;
3860   if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3861     T = TD->getUnderlyingType();
3862   else if (const auto *VD = dyn_cast<ValueDecl>(D))
3863     T = VD->getType();
3864   else
3865     llvm_unreachable("Unknown decl type for align_value");
3866 
3867   if (!T->isDependentType() && !T->isAnyPointerType() &&
3868       !T->isReferenceType() && !T->isMemberPointerType()) {
3869     Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3870       << &TmpAttr << T << D->getSourceRange();
3871     return;
3872   }
3873 
3874   if (!E->isValueDependent()) {
3875     llvm::APSInt Alignment;
3876     ExprResult ICE = VerifyIntegerConstantExpression(
3877         E, &Alignment, diag::err_align_value_attribute_argument_not_int);
3878     if (ICE.isInvalid())
3879       return;
3880 
3881     if (!Alignment.isPowerOf2()) {
3882       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3883         << E->getSourceRange();
3884       return;
3885     }
3886 
3887     D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3888     return;
3889   }
3890 
3891   // Save dependent expressions in the AST to be instantiated.
3892   D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3893 }
3894 
3895 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3896   // check the attribute arguments.
3897   if (AL.getNumArgs() > 1) {
3898     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3899     return;
3900   }
3901 
3902   if (AL.getNumArgs() == 0) {
3903     D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3904     return;
3905   }
3906 
3907   Expr *E = AL.getArgAsExpr(0);
3908   if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3909     S.Diag(AL.getEllipsisLoc(),
3910            diag::err_pack_expansion_without_parameter_packs);
3911     return;
3912   }
3913 
3914   if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3915     return;
3916 
3917   S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3918 }
3919 
3920 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
3921                           bool IsPackExpansion) {
3922   AlignedAttr TmpAttr(Context, CI, true, E);
3923   SourceLocation AttrLoc = CI.getLoc();
3924 
3925   // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3926   if (TmpAttr.isAlignas()) {
3927     // C++11 [dcl.align]p1:
3928     //   An alignment-specifier may be applied to a variable or to a class
3929     //   data member, but it shall not be applied to a bit-field, a function
3930     //   parameter, the formal parameter of a catch clause, or a variable
3931     //   declared with the register storage class specifier. An
3932     //   alignment-specifier may also be applied to the declaration of a class
3933     //   or enumeration type.
3934     // C11 6.7.5/2:
3935     //   An alignment attribute shall not be specified in a declaration of
3936     //   a typedef, or a bit-field, or a function, or a parameter, or an
3937     //   object declared with the register storage-class specifier.
3938     int DiagKind = -1;
3939     if (isa<ParmVarDecl>(D)) {
3940       DiagKind = 0;
3941     } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3942       if (VD->getStorageClass() == SC_Register)
3943         DiagKind = 1;
3944       if (VD->isExceptionVariable())
3945         DiagKind = 2;
3946     } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3947       if (FD->isBitField())
3948         DiagKind = 3;
3949     } else if (!isa<TagDecl>(D)) {
3950       Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3951         << (TmpAttr.isC11() ? ExpectedVariableOrField
3952                             : ExpectedVariableFieldOrTag);
3953       return;
3954     }
3955     if (DiagKind != -1) {
3956       Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3957         << &TmpAttr << DiagKind;
3958       return;
3959     }
3960   }
3961 
3962   if (E->isValueDependent()) {
3963     // We can't support a dependent alignment on a non-dependent type,
3964     // because we have no way to model that a type is "alignment-dependent"
3965     // but not dependent in any other way.
3966     if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3967       if (!TND->getUnderlyingType()->isDependentType()) {
3968         Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3969             << E->getSourceRange();
3970         return;
3971       }
3972     }
3973 
3974     // Save dependent expressions in the AST to be instantiated.
3975     AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
3976     AA->setPackExpansion(IsPackExpansion);
3977     D->addAttr(AA);
3978     return;
3979   }
3980 
3981   // FIXME: Cache the number on the AL object?
3982   llvm::APSInt Alignment;
3983   ExprResult ICE = VerifyIntegerConstantExpression(
3984       E, &Alignment, diag::err_aligned_attribute_argument_not_int);
3985   if (ICE.isInvalid())
3986     return;
3987 
3988   uint64_t AlignVal = Alignment.getZExtValue();
3989 
3990   // C++11 [dcl.align]p2:
3991   //   -- if the constant expression evaluates to zero, the alignment
3992   //      specifier shall have no effect
3993   // C11 6.7.5p6:
3994   //   An alignment specification of zero has no effect.
3995   if (!(TmpAttr.isAlignas() && !Alignment)) {
3996     if (!llvm::isPowerOf2_64(AlignVal)) {
3997       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3998         << E->getSourceRange();
3999       return;
4000     }
4001   }
4002 
4003   unsigned MaximumAlignment = Sema::MaximumAlignment;
4004   if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4005     MaximumAlignment = std::min(MaximumAlignment, 8192u);
4006   if (AlignVal > MaximumAlignment) {
4007     Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4008         << MaximumAlignment << E->getSourceRange();
4009     return;
4010   }
4011 
4012   if (Context.getTargetInfo().isTLSSupported()) {
4013     unsigned MaxTLSAlign =
4014         Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
4015             .getQuantity();
4016     const auto *VD = dyn_cast<VarDecl>(D);
4017     if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
4018         VD->getTLSKind() != VarDecl::TLS_None) {
4019       Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4020           << (unsigned)AlignVal << VD << MaxTLSAlign;
4021       return;
4022     }
4023   }
4024 
4025   AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4026   AA->setPackExpansion(IsPackExpansion);
4027   D->addAttr(AA);
4028 }
4029 
4030 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
4031                           TypeSourceInfo *TS, bool IsPackExpansion) {
4032   // FIXME: Cache the number on the AL object if non-dependent?
4033   // FIXME: Perform checking of type validity
4034   AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4035   AA->setPackExpansion(IsPackExpansion);
4036   D->addAttr(AA);
4037 }
4038 
4039 void Sema::CheckAlignasUnderalignment(Decl *D) {
4040   assert(D->hasAttrs() && "no attributes on decl");
4041 
4042   QualType UnderlyingTy, DiagTy;
4043   if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4044     UnderlyingTy = DiagTy = VD->getType();
4045   } else {
4046     UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4047     if (const auto *ED = dyn_cast<EnumDecl>(D))
4048       UnderlyingTy = ED->getIntegerType();
4049   }
4050   if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4051     return;
4052 
4053   // C++11 [dcl.align]p5, C11 6.7.5/4:
4054   //   The combined effect of all alignment attributes in a declaration shall
4055   //   not specify an alignment that is less strict than the alignment that
4056   //   would otherwise be required for the entity being declared.
4057   AlignedAttr *AlignasAttr = nullptr;
4058   AlignedAttr *LastAlignedAttr = nullptr;
4059   unsigned Align = 0;
4060   for (auto *I : D->specific_attrs<AlignedAttr>()) {
4061     if (I->isAlignmentDependent())
4062       return;
4063     if (I->isAlignas())
4064       AlignasAttr = I;
4065     Align = std::max(Align, I->getAlignment(Context));
4066     LastAlignedAttr = I;
4067   }
4068 
4069   if (Align && DiagTy->isSizelessType()) {
4070     Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4071         << LastAlignedAttr << DiagTy;
4072   } else if (AlignasAttr && Align) {
4073     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4074     CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4075     if (NaturalAlign > RequestedAlign)
4076       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4077         << DiagTy << (unsigned)NaturalAlign.getQuantity();
4078   }
4079 }
4080 
4081 bool Sema::checkMSInheritanceAttrOnDefinition(
4082     CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4083     MSInheritanceModel ExplicitModel) {
4084   assert(RD->hasDefinition() && "RD has no definition!");
4085 
4086   // We may not have seen base specifiers or any virtual methods yet.  We will
4087   // have to wait until the record is defined to catch any mismatches.
4088   if (!RD->getDefinition()->isCompleteDefinition())
4089     return false;
4090 
4091   // The unspecified model never matches what a definition could need.
4092   if (ExplicitModel == MSInheritanceModel::Unspecified)
4093     return false;
4094 
4095   if (BestCase) {
4096     if (RD->calculateInheritanceModel() == ExplicitModel)
4097       return false;
4098   } else {
4099     if (RD->calculateInheritanceModel() <= ExplicitModel)
4100       return false;
4101   }
4102 
4103   Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4104       << 0 /*definition*/;
4105   Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4106   return true;
4107 }
4108 
4109 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
4110 /// attribute.
4111 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4112                              bool &IntegerMode, bool &ComplexMode,
4113                              bool &ExplicitIEEE) {
4114   IntegerMode = true;
4115   ComplexMode = false;
4116   switch (Str.size()) {
4117   case 2:
4118     switch (Str[0]) {
4119     case 'Q':
4120       DestWidth = 8;
4121       break;
4122     case 'H':
4123       DestWidth = 16;
4124       break;
4125     case 'S':
4126       DestWidth = 32;
4127       break;
4128     case 'D':
4129       DestWidth = 64;
4130       break;
4131     case 'X':
4132       DestWidth = 96;
4133       break;
4134     case 'K': // KFmode - IEEE quad precision (__float128)
4135       ExplicitIEEE = true;
4136       DestWidth = Str[1] == 'I' ? 0 : 128;
4137       break;
4138     case 'T':
4139       ExplicitIEEE = false;
4140       DestWidth = 128;
4141       break;
4142     }
4143     if (Str[1] == 'F') {
4144       IntegerMode = false;
4145     } else if (Str[1] == 'C') {
4146       IntegerMode = false;
4147       ComplexMode = true;
4148     } else if (Str[1] != 'I') {
4149       DestWidth = 0;
4150     }
4151     break;
4152   case 4:
4153     // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4154     // pointer on PIC16 and other embedded platforms.
4155     if (Str == "word")
4156       DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4157     else if (Str == "byte")
4158       DestWidth = S.Context.getTargetInfo().getCharWidth();
4159     break;
4160   case 7:
4161     if (Str == "pointer")
4162       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
4163     break;
4164   case 11:
4165     if (Str == "unwind_word")
4166       DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4167     break;
4168   }
4169 }
4170 
4171 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4172 /// type.
4173 ///
4174 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4175 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4176 /// HImode, not an intermediate pointer.
4177 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4178   // This attribute isn't documented, but glibc uses it.  It changes
4179   // the width of an int or unsigned int to the specified size.
4180   if (!AL.isArgIdent(0)) {
4181     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4182         << AL << AANT_ArgumentIdentifier;
4183     return;
4184   }
4185 
4186   IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4187 
4188   S.AddModeAttr(D, AL, Name);
4189 }
4190 
4191 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
4192                        IdentifierInfo *Name, bool InInstantiation) {
4193   StringRef Str = Name->getName();
4194   normalizeName(Str);
4195   SourceLocation AttrLoc = CI.getLoc();
4196 
4197   unsigned DestWidth = 0;
4198   bool IntegerMode = true;
4199   bool ComplexMode = false;
4200   bool ExplicitIEEE = false;
4201   llvm::APInt VectorSize(64, 0);
4202   if (Str.size() >= 4 && Str[0] == 'V') {
4203     // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4204     size_t StrSize = Str.size();
4205     size_t VectorStringLength = 0;
4206     while ((VectorStringLength + 1) < StrSize &&
4207            isdigit(Str[VectorStringLength + 1]))
4208       ++VectorStringLength;
4209     if (VectorStringLength &&
4210         !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4211         VectorSize.isPowerOf2()) {
4212       parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4213                        IntegerMode, ComplexMode, ExplicitIEEE);
4214       // Avoid duplicate warning from template instantiation.
4215       if (!InInstantiation)
4216         Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4217     } else {
4218       VectorSize = 0;
4219     }
4220   }
4221 
4222   if (!VectorSize)
4223     parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4224                      ExplicitIEEE);
4225 
4226   // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4227   // and friends, at least with glibc.
4228   // FIXME: Make sure floating-point mappings are accurate
4229   // FIXME: Support XF and TF types
4230   if (!DestWidth) {
4231     Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4232     return;
4233   }
4234 
4235   QualType OldTy;
4236   if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4237     OldTy = TD->getUnderlyingType();
4238   else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4239     // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4240     // Try to get type from enum declaration, default to int.
4241     OldTy = ED->getIntegerType();
4242     if (OldTy.isNull())
4243       OldTy = Context.IntTy;
4244   } else
4245     OldTy = cast<ValueDecl>(D)->getType();
4246 
4247   if (OldTy->isDependentType()) {
4248     D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4249     return;
4250   }
4251 
4252   // Base type can also be a vector type (see PR17453).
4253   // Distinguish between base type and base element type.
4254   QualType OldElemTy = OldTy;
4255   if (const auto *VT = OldTy->getAs<VectorType>())
4256     OldElemTy = VT->getElementType();
4257 
4258   // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4259   // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4260   // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4261   if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4262       VectorSize.getBoolValue()) {
4263     Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4264     return;
4265   }
4266   bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4267                                 !OldElemTy->isExtIntType()) ||
4268                                OldElemTy->getAs<EnumType>();
4269 
4270   if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4271       !IntegralOrAnyEnumType)
4272     Diag(AttrLoc, diag::err_mode_not_primitive);
4273   else if (IntegerMode) {
4274     if (!IntegralOrAnyEnumType)
4275       Diag(AttrLoc, diag::err_mode_wrong_type);
4276   } else if (ComplexMode) {
4277     if (!OldElemTy->isComplexType())
4278       Diag(AttrLoc, diag::err_mode_wrong_type);
4279   } else {
4280     if (!OldElemTy->isFloatingType())
4281       Diag(AttrLoc, diag::err_mode_wrong_type);
4282   }
4283 
4284   QualType NewElemTy;
4285 
4286   if (IntegerMode)
4287     NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4288                                               OldElemTy->isSignedIntegerType());
4289   else
4290     NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitIEEE);
4291 
4292   if (NewElemTy.isNull()) {
4293     Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4294     return;
4295   }
4296 
4297   if (ComplexMode) {
4298     NewElemTy = Context.getComplexType(NewElemTy);
4299   }
4300 
4301   QualType NewTy = NewElemTy;
4302   if (VectorSize.getBoolValue()) {
4303     NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4304                                   VectorType::GenericVector);
4305   } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4306     // Complex machine mode does not support base vector types.
4307     if (ComplexMode) {
4308       Diag(AttrLoc, diag::err_complex_mode_vector_type);
4309       return;
4310     }
4311     unsigned NumElements = Context.getTypeSize(OldElemTy) *
4312                            OldVT->getNumElements() /
4313                            Context.getTypeSize(NewElemTy);
4314     NewTy =
4315         Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4316   }
4317 
4318   if (NewTy.isNull()) {
4319     Diag(AttrLoc, diag::err_mode_wrong_type);
4320     return;
4321   }
4322 
4323   // Install the new type.
4324   if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4325     TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4326   else if (auto *ED = dyn_cast<EnumDecl>(D))
4327     ED->setIntegerType(NewTy);
4328   else
4329     cast<ValueDecl>(D)->setType(NewTy);
4330 
4331   D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4332 }
4333 
4334 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4335   D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4336 }
4337 
4338 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4339                                               const AttributeCommonInfo &CI,
4340                                               const IdentifierInfo *Ident) {
4341   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4342     Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4343     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4344     return nullptr;
4345   }
4346 
4347   if (D->hasAttr<AlwaysInlineAttr>())
4348     return nullptr;
4349 
4350   return ::new (Context) AlwaysInlineAttr(Context, CI);
4351 }
4352 
4353 CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
4354   if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4355     return nullptr;
4356 
4357   return ::new (Context) CommonAttr(Context, AL);
4358 }
4359 
4360 CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
4361   if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4362     return nullptr;
4363 
4364   return ::new (Context) CommonAttr(Context, AL);
4365 }
4366 
4367 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4368                                                     const ParsedAttr &AL) {
4369   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4370     // Attribute applies to Var but not any subclass of it (like ParmVar,
4371     // ImplicitParm or VarTemplateSpecialization).
4372     if (VD->getKind() != Decl::Var) {
4373       Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4374           << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4375                                             : ExpectedVariableOrFunction);
4376       return nullptr;
4377     }
4378     // Attribute does not apply to non-static local variables.
4379     if (VD->hasLocalStorage()) {
4380       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4381       return nullptr;
4382     }
4383   }
4384 
4385   if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4386     return nullptr;
4387 
4388   return ::new (Context) InternalLinkageAttr(Context, AL);
4389 }
4390 InternalLinkageAttr *
4391 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4392   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4393     // Attribute applies to Var but not any subclass of it (like ParmVar,
4394     // ImplicitParm or VarTemplateSpecialization).
4395     if (VD->getKind() != Decl::Var) {
4396       Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4397           << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4398                                              : ExpectedVariableOrFunction);
4399       return nullptr;
4400     }
4401     // Attribute does not apply to non-static local variables.
4402     if (VD->hasLocalStorage()) {
4403       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4404       return nullptr;
4405     }
4406   }
4407 
4408   if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4409     return nullptr;
4410 
4411   return ::new (Context) InternalLinkageAttr(Context, AL);
4412 }
4413 
4414 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4415   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4416     Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4417     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4418     return nullptr;
4419   }
4420 
4421   if (D->hasAttr<MinSizeAttr>())
4422     return nullptr;
4423 
4424   return ::new (Context) MinSizeAttr(Context, CI);
4425 }
4426 
4427 NoSpeculativeLoadHardeningAttr *Sema::mergeNoSpeculativeLoadHardeningAttr(
4428     Decl *D, const NoSpeculativeLoadHardeningAttr &AL) {
4429   if (checkAttrMutualExclusion<SpeculativeLoadHardeningAttr>(*this, D, AL))
4430     return nullptr;
4431 
4432   return ::new (Context) NoSpeculativeLoadHardeningAttr(Context, AL);
4433 }
4434 
4435 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
4436                                         StringRef Name) {
4437   if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
4438     if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
4439       Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
4440           << PrevSNA << &SNA;
4441       Diag(SNA.getLoc(), diag::note_conflicting_attribute);
4442     }
4443 
4444     D->dropAttr<SwiftNameAttr>();
4445   }
4446   return ::new (Context) SwiftNameAttr(Context, SNA, Name);
4447 }
4448 
4449 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4450                                               const AttributeCommonInfo &CI) {
4451   if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4452     Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4453     Diag(CI.getLoc(), diag::note_conflicting_attribute);
4454     D->dropAttr<AlwaysInlineAttr>();
4455   }
4456   if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4457     Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4458     Diag(CI.getLoc(), diag::note_conflicting_attribute);
4459     D->dropAttr<MinSizeAttr>();
4460   }
4461 
4462   if (D->hasAttr<OptimizeNoneAttr>())
4463     return nullptr;
4464 
4465   return ::new (Context) OptimizeNoneAttr(Context, CI);
4466 }
4467 
4468 SpeculativeLoadHardeningAttr *Sema::mergeSpeculativeLoadHardeningAttr(
4469     Decl *D, const SpeculativeLoadHardeningAttr &AL) {
4470   if (checkAttrMutualExclusion<NoSpeculativeLoadHardeningAttr>(*this, D, AL))
4471     return nullptr;
4472 
4473   return ::new (Context) SpeculativeLoadHardeningAttr(Context, AL);
4474 }
4475 
4476 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4477   if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
4478     return;
4479 
4480   if (AlwaysInlineAttr *Inline =
4481           S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4482     D->addAttr(Inline);
4483 }
4484 
4485 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4486   if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4487     D->addAttr(MinSize);
4488 }
4489 
4490 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4491   if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4492     D->addAttr(Optnone);
4493 }
4494 
4495 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4496   if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
4497     return;
4498   const auto *VD = cast<VarDecl>(D);
4499   if (VD->hasLocalStorage()) {
4500     S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4501     return;
4502   }
4503   D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4504 }
4505 
4506 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4507   if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
4508     return;
4509   const auto *VD = cast<VarDecl>(D);
4510   // extern __shared__ is only allowed on arrays with no length (e.g.
4511   // "int x[]").
4512   if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4513       !isa<IncompleteArrayType>(VD->getType())) {
4514     S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4515     return;
4516   }
4517   if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4518       S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4519           << S.CurrentCUDATarget())
4520     return;
4521   D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4522 }
4523 
4524 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4525   if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
4526       checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
4527     return;
4528   }
4529   const auto *FD = cast<FunctionDecl>(D);
4530   if (!FD->getReturnType()->isVoidType() &&
4531       !FD->getReturnType()->getAs<AutoType>() &&
4532       !FD->getReturnType()->isInstantiationDependentType()) {
4533     SourceRange RTRange = FD->getReturnTypeSourceRange();
4534     S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4535         << FD->getType()
4536         << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4537                               : FixItHint());
4538     return;
4539   }
4540   if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4541     if (Method->isInstance()) {
4542       S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4543           << Method;
4544       return;
4545     }
4546     S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4547   }
4548   // Only warn for "inline" when compiling for host, to cut down on noise.
4549   if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4550     S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4551 
4552   D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4553   // In host compilation the kernel is emitted as a stub function, which is
4554   // a helper function for launching the kernel. The instructions in the helper
4555   // function has nothing to do with the source code of the kernel. Do not emit
4556   // debug info for the stub function to avoid confusing the debugger.
4557   if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
4558     D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
4559 }
4560 
4561 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4562   if (checkAttrMutualExclusion<CUDAGlobalAttr>(S, D, AL)) {
4563     return;
4564   }
4565 
4566   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4567     if (VD->hasLocalStorage()) {
4568       S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4569       return;
4570     }
4571   }
4572   D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
4573 }
4574 
4575 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4576   const auto *Fn = cast<FunctionDecl>(D);
4577   if (!Fn->isInlineSpecified()) {
4578     S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4579     return;
4580   }
4581 
4582   if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
4583     S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4584 
4585   D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4586 }
4587 
4588 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4589   if (hasDeclarator(D)) return;
4590 
4591   // Diagnostic is emitted elsewhere: here we store the (valid) AL
4592   // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4593   CallingConv CC;
4594   if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4595     return;
4596 
4597   if (!isa<ObjCMethodDecl>(D)) {
4598     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4599         << AL << ExpectedFunctionOrMethod;
4600     return;
4601   }
4602 
4603   switch (AL.getKind()) {
4604   case ParsedAttr::AT_FastCall:
4605     D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
4606     return;
4607   case ParsedAttr::AT_StdCall:
4608     D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
4609     return;
4610   case ParsedAttr::AT_ThisCall:
4611     D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
4612     return;
4613   case ParsedAttr::AT_CDecl:
4614     D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
4615     return;
4616   case ParsedAttr::AT_Pascal:
4617     D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
4618     return;
4619   case ParsedAttr::AT_SwiftCall:
4620     D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
4621     return;
4622   case ParsedAttr::AT_VectorCall:
4623     D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
4624     return;
4625   case ParsedAttr::AT_MSABI:
4626     D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
4627     return;
4628   case ParsedAttr::AT_SysVABI:
4629     D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
4630     return;
4631   case ParsedAttr::AT_RegCall:
4632     D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
4633     return;
4634   case ParsedAttr::AT_Pcs: {
4635     PcsAttr::PCSType PCS;
4636     switch (CC) {
4637     case CC_AAPCS:
4638       PCS = PcsAttr::AAPCS;
4639       break;
4640     case CC_AAPCS_VFP:
4641       PCS = PcsAttr::AAPCS_VFP;
4642       break;
4643     default:
4644       llvm_unreachable("unexpected calling convention in pcs attribute");
4645     }
4646 
4647     D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
4648     return;
4649   }
4650   case ParsedAttr::AT_AArch64VectorPcs:
4651     D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
4652     return;
4653   case ParsedAttr::AT_IntelOclBicc:
4654     D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
4655     return;
4656   case ParsedAttr::AT_PreserveMost:
4657     D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
4658     return;
4659   case ParsedAttr::AT_PreserveAll:
4660     D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
4661     return;
4662   default:
4663     llvm_unreachable("unexpected attribute kind");
4664   }
4665 }
4666 
4667 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4668   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4669     return;
4670 
4671   std::vector<StringRef> DiagnosticIdentifiers;
4672   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4673     StringRef RuleName;
4674 
4675     if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4676       return;
4677 
4678     // FIXME: Warn if the rule name is unknown. This is tricky because only
4679     // clang-tidy knows about available rules.
4680     DiagnosticIdentifiers.push_back(RuleName);
4681   }
4682   D->addAttr(::new (S.Context)
4683                  SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
4684                               DiagnosticIdentifiers.size()));
4685 }
4686 
4687 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4688   TypeSourceInfo *DerefTypeLoc = nullptr;
4689   QualType ParmType;
4690   if (AL.hasParsedType()) {
4691     ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
4692 
4693     unsigned SelectIdx = ~0U;
4694     if (ParmType->isReferenceType())
4695       SelectIdx = 0;
4696     else if (ParmType->isArrayType())
4697       SelectIdx = 1;
4698 
4699     if (SelectIdx != ~0U) {
4700       S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
4701           << SelectIdx << AL;
4702       return;
4703     }
4704   }
4705 
4706   // To check if earlier decl attributes do not conflict the newly parsed ones
4707   // we always add (and check) the attribute to the cannonical decl.
4708   D = D->getCanonicalDecl();
4709   if (AL.getKind() == ParsedAttr::AT_Owner) {
4710     if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
4711       return;
4712     if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
4713       const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
4714                                           ? OAttr->getDerefType().getTypePtr()
4715                                           : nullptr;
4716       if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4717         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4718             << AL << OAttr;
4719         S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
4720       }
4721       return;
4722     }
4723     for (Decl *Redecl : D->redecls()) {
4724       Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
4725     }
4726   } else {
4727     if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
4728       return;
4729     if (const auto *PAttr = D->getAttr<PointerAttr>()) {
4730       const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
4731                                           ? PAttr->getDerefType().getTypePtr()
4732                                           : nullptr;
4733       if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4734         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4735             << AL << PAttr;
4736         S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
4737       }
4738       return;
4739     }
4740     for (Decl *Redecl : D->redecls()) {
4741       Redecl->addAttr(::new (S.Context)
4742                           PointerAttr(S.Context, AL, DerefTypeLoc));
4743     }
4744   }
4745 }
4746 
4747 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4748                                 const FunctionDecl *FD) {
4749   if (Attrs.isInvalid())
4750     return true;
4751 
4752   if (Attrs.hasProcessingCache()) {
4753     CC = (CallingConv) Attrs.getProcessingCache();
4754     return false;
4755   }
4756 
4757   unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4758   if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4759     Attrs.setInvalid();
4760     return true;
4761   }
4762 
4763   // TODO: diagnose uses of these conventions on the wrong target.
4764   switch (Attrs.getKind()) {
4765   case ParsedAttr::AT_CDecl:
4766     CC = CC_C;
4767     break;
4768   case ParsedAttr::AT_FastCall:
4769     CC = CC_X86FastCall;
4770     break;
4771   case ParsedAttr::AT_StdCall:
4772     CC = CC_X86StdCall;
4773     break;
4774   case ParsedAttr::AT_ThisCall:
4775     CC = CC_X86ThisCall;
4776     break;
4777   case ParsedAttr::AT_Pascal:
4778     CC = CC_X86Pascal;
4779     break;
4780   case ParsedAttr::AT_SwiftCall:
4781     CC = CC_Swift;
4782     break;
4783   case ParsedAttr::AT_VectorCall:
4784     CC = CC_X86VectorCall;
4785     break;
4786   case ParsedAttr::AT_AArch64VectorPcs:
4787     CC = CC_AArch64VectorCall;
4788     break;
4789   case ParsedAttr::AT_RegCall:
4790     CC = CC_X86RegCall;
4791     break;
4792   case ParsedAttr::AT_MSABI:
4793     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4794                                                              CC_Win64;
4795     break;
4796   case ParsedAttr::AT_SysVABI:
4797     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4798                                                              CC_C;
4799     break;
4800   case ParsedAttr::AT_Pcs: {
4801     StringRef StrRef;
4802     if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4803       Attrs.setInvalid();
4804       return true;
4805     }
4806     if (StrRef == "aapcs") {
4807       CC = CC_AAPCS;
4808       break;
4809     } else if (StrRef == "aapcs-vfp") {
4810       CC = CC_AAPCS_VFP;
4811       break;
4812     }
4813 
4814     Attrs.setInvalid();
4815     Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4816     return true;
4817   }
4818   case ParsedAttr::AT_IntelOclBicc:
4819     CC = CC_IntelOclBicc;
4820     break;
4821   case ParsedAttr::AT_PreserveMost:
4822     CC = CC_PreserveMost;
4823     break;
4824   case ParsedAttr::AT_PreserveAll:
4825     CC = CC_PreserveAll;
4826     break;
4827   default: llvm_unreachable("unexpected attribute kind");
4828   }
4829 
4830   TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
4831   const TargetInfo &TI = Context.getTargetInfo();
4832   // CUDA functions may have host and/or device attributes which indicate
4833   // their targeted execution environment, therefore the calling convention
4834   // of functions in CUDA should be checked against the target deduced based
4835   // on their host/device attributes.
4836   if (LangOpts.CUDA) {
4837     auto *Aux = Context.getAuxTargetInfo();
4838     auto CudaTarget = IdentifyCUDATarget(FD);
4839     bool CheckHost = false, CheckDevice = false;
4840     switch (CudaTarget) {
4841     case CFT_HostDevice:
4842       CheckHost = true;
4843       CheckDevice = true;
4844       break;
4845     case CFT_Host:
4846       CheckHost = true;
4847       break;
4848     case CFT_Device:
4849     case CFT_Global:
4850       CheckDevice = true;
4851       break;
4852     case CFT_InvalidTarget:
4853       llvm_unreachable("unexpected cuda target");
4854     }
4855     auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
4856     auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
4857     if (CheckHost && HostTI)
4858       A = HostTI->checkCallingConvention(CC);
4859     if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
4860       A = DeviceTI->checkCallingConvention(CC);
4861   } else {
4862     A = TI.checkCallingConvention(CC);
4863   }
4864 
4865   switch (A) {
4866   case TargetInfo::CCCR_OK:
4867     break;
4868 
4869   case TargetInfo::CCCR_Ignore:
4870     // Treat an ignored convention as if it was an explicit C calling convention
4871     // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
4872     // that command line flags that change the default convention to
4873     // __vectorcall don't affect declarations marked __stdcall.
4874     CC = CC_C;
4875     break;
4876 
4877   case TargetInfo::CCCR_Error:
4878     Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
4879         << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4880     break;
4881 
4882   case TargetInfo::CCCR_Warning: {
4883     Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
4884         << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4885 
4886     // This convention is not valid for the target. Use the default function or
4887     // method calling convention.
4888     bool IsCXXMethod = false, IsVariadic = false;
4889     if (FD) {
4890       IsCXXMethod = FD->isCXXInstanceMember();
4891       IsVariadic = FD->isVariadic();
4892     }
4893     CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4894     break;
4895   }
4896   }
4897 
4898   Attrs.setProcessingCache((unsigned) CC);
4899   return false;
4900 }
4901 
4902 /// Pointer-like types in the default address space.
4903 static bool isValidSwiftContextType(QualType Ty) {
4904   if (!Ty->hasPointerRepresentation())
4905     return Ty->isDependentType();
4906   return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4907 }
4908 
4909 /// Pointers and references in the default address space.
4910 static bool isValidSwiftIndirectResultType(QualType Ty) {
4911   if (const auto *PtrType = Ty->getAs<PointerType>()) {
4912     Ty = PtrType->getPointeeType();
4913   } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4914     Ty = RefType->getPointeeType();
4915   } else {
4916     return Ty->isDependentType();
4917   }
4918   return Ty.getAddressSpace() == LangAS::Default;
4919 }
4920 
4921 /// Pointers and references to pointers in the default address space.
4922 static bool isValidSwiftErrorResultType(QualType Ty) {
4923   if (const auto *PtrType = Ty->getAs<PointerType>()) {
4924     Ty = PtrType->getPointeeType();
4925   } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4926     Ty = RefType->getPointeeType();
4927   } else {
4928     return Ty->isDependentType();
4929   }
4930   if (!Ty.getQualifiers().empty())
4931     return false;
4932   return isValidSwiftContextType(Ty);
4933 }
4934 
4935 void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
4936                                ParameterABI abi) {
4937 
4938   QualType type = cast<ParmVarDecl>(D)->getType();
4939 
4940   if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4941     if (existingAttr->getABI() != abi) {
4942       Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
4943           << getParameterABISpelling(abi) << existingAttr;
4944       Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4945       return;
4946     }
4947   }
4948 
4949   switch (abi) {
4950   case ParameterABI::Ordinary:
4951     llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4952 
4953   case ParameterABI::SwiftContext:
4954     if (!isValidSwiftContextType(type)) {
4955       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4956           << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
4957     }
4958     D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
4959     return;
4960 
4961   case ParameterABI::SwiftErrorResult:
4962     if (!isValidSwiftErrorResultType(type)) {
4963       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4964           << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
4965     }
4966     D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
4967     return;
4968 
4969   case ParameterABI::SwiftIndirectResult:
4970     if (!isValidSwiftIndirectResultType(type)) {
4971       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4972           << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
4973     }
4974     D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
4975     return;
4976   }
4977   llvm_unreachable("bad parameter ABI attribute");
4978 }
4979 
4980 /// Checks a regparm attribute, returning true if it is ill-formed and
4981 /// otherwise setting numParams to the appropriate value.
4982 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4983   if (AL.isInvalid())
4984     return true;
4985 
4986   if (!checkAttributeNumArgs(*this, AL, 1)) {
4987     AL.setInvalid();
4988     return true;
4989   }
4990 
4991   uint32_t NP;
4992   Expr *NumParamsExpr = AL.getArgAsExpr(0);
4993   if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4994     AL.setInvalid();
4995     return true;
4996   }
4997 
4998   if (Context.getTargetInfo().getRegParmMax() == 0) {
4999     Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
5000       << NumParamsExpr->getSourceRange();
5001     AL.setInvalid();
5002     return true;
5003   }
5004 
5005   numParams = NP;
5006   if (numParams > Context.getTargetInfo().getRegParmMax()) {
5007     Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
5008       << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
5009     AL.setInvalid();
5010     return true;
5011   }
5012 
5013   return false;
5014 }
5015 
5016 // Checks whether an argument of launch_bounds attribute is
5017 // acceptable, performs implicit conversion to Rvalue, and returns
5018 // non-nullptr Expr result on success. Otherwise, it returns nullptr
5019 // and may output an error.
5020 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
5021                                      const CUDALaunchBoundsAttr &AL,
5022                                      const unsigned Idx) {
5023   if (S.DiagnoseUnexpandedParameterPack(E))
5024     return nullptr;
5025 
5026   // Accept template arguments for now as they depend on something else.
5027   // We'll get to check them when they eventually get instantiated.
5028   if (E->isValueDependent())
5029     return E;
5030 
5031   Optional<llvm::APSInt> I = llvm::APSInt(64);
5032   if (!(I = E->getIntegerConstantExpr(S.Context))) {
5033     S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
5034         << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
5035     return nullptr;
5036   }
5037   // Make sure we can fit it in 32 bits.
5038   if (!I->isIntN(32)) {
5039     S.Diag(E->getExprLoc(), diag::err_ice_too_large)
5040         << I->toString(10, false) << 32 << /* Unsigned */ 1;
5041     return nullptr;
5042   }
5043   if (*I < 0)
5044     S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
5045         << &AL << Idx << E->getSourceRange();
5046 
5047   // We may need to perform implicit conversion of the argument.
5048   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5049       S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
5050   ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
5051   assert(!ValArg.isInvalid() &&
5052          "Unexpected PerformCopyInitialization() failure.");
5053 
5054   return ValArg.getAs<Expr>();
5055 }
5056 
5057 void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5058                                Expr *MaxThreads, Expr *MinBlocks) {
5059   CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks);
5060   MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
5061   if (MaxThreads == nullptr)
5062     return;
5063 
5064   if (MinBlocks) {
5065     MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
5066     if (MinBlocks == nullptr)
5067       return;
5068   }
5069 
5070   D->addAttr(::new (Context)
5071                  CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks));
5072 }
5073 
5074 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5075   if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
5076       !checkAttributeAtMostNumArgs(S, AL, 2))
5077     return;
5078 
5079   S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
5080                         AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr);
5081 }
5082 
5083 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
5084                                           const ParsedAttr &AL) {
5085   if (!AL.isArgIdent(0)) {
5086     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5087         << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
5088     return;
5089   }
5090 
5091   ParamIdx ArgumentIdx;
5092   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
5093                                            ArgumentIdx))
5094     return;
5095 
5096   ParamIdx TypeTagIdx;
5097   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
5098                                            TypeTagIdx))
5099     return;
5100 
5101   bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
5102   if (IsPointer) {
5103     // Ensure that buffer has a pointer type.
5104     unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
5105     if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
5106         !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
5107       S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
5108   }
5109 
5110   D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
5111       S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
5112       IsPointer));
5113 }
5114 
5115 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
5116                                          const ParsedAttr &AL) {
5117   if (!AL.isArgIdent(0)) {
5118     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5119         << AL << 1 << AANT_ArgumentIdentifier;
5120     return;
5121   }
5122 
5123   if (!checkAttributeNumArgs(S, AL, 1))
5124     return;
5125 
5126   if (!isa<VarDecl>(D)) {
5127     S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
5128         << AL << ExpectedVariable;
5129     return;
5130   }
5131 
5132   IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
5133   TypeSourceInfo *MatchingCTypeLoc = nullptr;
5134   S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
5135   assert(MatchingCTypeLoc && "no type source info for attribute argument");
5136 
5137   D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
5138       S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
5139       AL.getMustBeNull()));
5140 }
5141 
5142 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5143   ParamIdx ArgCount;
5144 
5145   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
5146                                            ArgCount,
5147                                            true /* CanIndexImplicitThis */))
5148     return;
5149 
5150   // ArgCount isn't a parameter index [0;n), it's a count [1;n]
5151   D->addAttr(::new (S.Context)
5152                  XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
5153 }
5154 
5155 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
5156                                              const ParsedAttr &AL) {
5157   uint32_t Count = 0, Offset = 0;
5158   if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
5159     return;
5160   if (AL.getNumArgs() == 2) {
5161     Expr *Arg = AL.getArgAsExpr(1);
5162     if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
5163       return;
5164     if (Count < Offset) {
5165       S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
5166           << &AL << 0 << Count << Arg->getBeginLoc();
5167       return;
5168     }
5169   }
5170   D->addAttr(::new (S.Context)
5171                  PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
5172 }
5173 
5174 namespace {
5175 struct IntrinToName {
5176   uint32_t Id;
5177   int32_t FullName;
5178   int32_t ShortName;
5179 };
5180 } // unnamed namespace
5181 
5182 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
5183                                  ArrayRef<IntrinToName> Map,
5184                                  const char *IntrinNames) {
5185   if (AliasName.startswith("__arm_"))
5186     AliasName = AliasName.substr(6);
5187   const IntrinToName *It = std::lower_bound(
5188       Map.begin(), Map.end(), BuiltinID,
5189       [](const IntrinToName &L, unsigned Id) { return L.Id < Id; });
5190   if (It == Map.end() || It->Id != BuiltinID)
5191     return false;
5192   StringRef FullName(&IntrinNames[It->FullName]);
5193   if (AliasName == FullName)
5194     return true;
5195   if (It->ShortName == -1)
5196     return false;
5197   StringRef ShortName(&IntrinNames[It->ShortName]);
5198   return AliasName == ShortName;
5199 }
5200 
5201 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5202 #include "clang/Basic/arm_mve_builtin_aliases.inc"
5203   // The included file defines:
5204   // - ArrayRef<IntrinToName> Map
5205   // - const char IntrinNames[]
5206   return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5207 }
5208 
5209 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
5210 #include "clang/Basic/arm_cde_builtin_aliases.inc"
5211   return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5212 }
5213 
5214 static bool ArmSveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5215   switch (BuiltinID) {
5216   default:
5217     return false;
5218 #define GET_SVE_BUILTINS
5219 #define BUILTIN(name, types, attr) case SVE::BI##name:
5220 #include "clang/Basic/arm_sve_builtins.inc"
5221     return true;
5222   }
5223 }
5224 
5225 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5226   if (!AL.isArgIdent(0)) {
5227     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5228         << AL << 1 << AANT_ArgumentIdentifier;
5229     return;
5230   }
5231 
5232   IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5233   unsigned BuiltinID = Ident->getBuiltinID();
5234   StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5235 
5236   bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5237   if ((IsAArch64 && !ArmSveAliasValid(BuiltinID, AliasName)) ||
5238       (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) &&
5239        !ArmCdeAliasValid(BuiltinID, AliasName))) {
5240     S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
5241     return;
5242   }
5243 
5244   D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
5245 }
5246 
5247 //===----------------------------------------------------------------------===//
5248 // Checker-specific attribute handlers.
5249 //===----------------------------------------------------------------------===//
5250 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
5251   return QT->isDependentType() || QT->isObjCRetainableType();
5252 }
5253 
5254 static bool isValidSubjectOfNSAttribute(QualType QT) {
5255   return QT->isDependentType() || QT->isObjCObjectPointerType() ||
5256          QT->isObjCNSObjectType();
5257 }
5258 
5259 static bool isValidSubjectOfCFAttribute(QualType QT) {
5260   return QT->isDependentType() || QT->isPointerType() ||
5261          isValidSubjectOfNSAttribute(QT);
5262 }
5263 
5264 static bool isValidSubjectOfOSAttribute(QualType QT) {
5265   if (QT->isDependentType())
5266     return true;
5267   QualType PT = QT->getPointeeType();
5268   return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
5269 }
5270 
5271 void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
5272                             RetainOwnershipKind K,
5273                             bool IsTemplateInstantiation) {
5274   ValueDecl *VD = cast<ValueDecl>(D);
5275   switch (K) {
5276   case RetainOwnershipKind::OS:
5277     handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
5278         *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
5279         diag::warn_ns_attribute_wrong_parameter_type,
5280         /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
5281     return;
5282   case RetainOwnershipKind::NS:
5283     handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
5284         *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
5285 
5286         // These attributes are normally just advisory, but in ARC, ns_consumed
5287         // is significant.  Allow non-dependent code to contain inappropriate
5288         // attributes even in ARC, but require template instantiations to be
5289         // set up correctly.
5290         ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
5291              ? diag::err_ns_attribute_wrong_parameter_type
5292              : diag::warn_ns_attribute_wrong_parameter_type),
5293         /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
5294     return;
5295   case RetainOwnershipKind::CF:
5296     handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
5297         *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
5298         diag::warn_ns_attribute_wrong_parameter_type,
5299         /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
5300     return;
5301   }
5302 }
5303 
5304 static Sema::RetainOwnershipKind
5305 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
5306   switch (AL.getKind()) {
5307   case ParsedAttr::AT_CFConsumed:
5308   case ParsedAttr::AT_CFReturnsRetained:
5309   case ParsedAttr::AT_CFReturnsNotRetained:
5310     return Sema::RetainOwnershipKind::CF;
5311   case ParsedAttr::AT_OSConsumesThis:
5312   case ParsedAttr::AT_OSConsumed:
5313   case ParsedAttr::AT_OSReturnsRetained:
5314   case ParsedAttr::AT_OSReturnsNotRetained:
5315   case ParsedAttr::AT_OSReturnsRetainedOnZero:
5316   case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
5317     return Sema::RetainOwnershipKind::OS;
5318   case ParsedAttr::AT_NSConsumesSelf:
5319   case ParsedAttr::AT_NSConsumed:
5320   case ParsedAttr::AT_NSReturnsRetained:
5321   case ParsedAttr::AT_NSReturnsNotRetained:
5322   case ParsedAttr::AT_NSReturnsAutoreleased:
5323     return Sema::RetainOwnershipKind::NS;
5324   default:
5325     llvm_unreachable("Wrong argument supplied");
5326   }
5327 }
5328 
5329 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
5330   if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
5331     return false;
5332 
5333   Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
5334       << "'ns_returns_retained'" << 0 << 0;
5335   return true;
5336 }
5337 
5338 /// \return whether the parameter is a pointer to OSObject pointer.
5339 static bool isValidOSObjectOutParameter(const Decl *D) {
5340   const auto *PVD = dyn_cast<ParmVarDecl>(D);
5341   if (!PVD)
5342     return false;
5343   QualType QT = PVD->getType();
5344   QualType PT = QT->getPointeeType();
5345   return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
5346 }
5347 
5348 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
5349                                         const ParsedAttr &AL) {
5350   QualType ReturnType;
5351   Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
5352 
5353   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5354     ReturnType = MD->getReturnType();
5355   } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
5356              (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
5357     return; // ignore: was handled as a type attribute
5358   } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
5359     ReturnType = PD->getType();
5360   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5361     ReturnType = FD->getReturnType();
5362   } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
5363     // Attributes on parameters are used for out-parameters,
5364     // passed as pointers-to-pointers.
5365     unsigned DiagID = K == Sema::RetainOwnershipKind::CF
5366             ? /*pointer-to-CF-pointer*/2
5367             : /*pointer-to-OSObject-pointer*/3;
5368     ReturnType = Param->getType()->getPointeeType();
5369     if (ReturnType.isNull()) {
5370       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5371           << AL << DiagID << AL.getRange();
5372       return;
5373     }
5374   } else if (AL.isUsedAsTypeAttr()) {
5375     return;
5376   } else {
5377     AttributeDeclKind ExpectedDeclKind;
5378     switch (AL.getKind()) {
5379     default: llvm_unreachable("invalid ownership attribute");
5380     case ParsedAttr::AT_NSReturnsRetained:
5381     case ParsedAttr::AT_NSReturnsAutoreleased:
5382     case ParsedAttr::AT_NSReturnsNotRetained:
5383       ExpectedDeclKind = ExpectedFunctionOrMethod;
5384       break;
5385 
5386     case ParsedAttr::AT_OSReturnsRetained:
5387     case ParsedAttr::AT_OSReturnsNotRetained:
5388     case ParsedAttr::AT_CFReturnsRetained:
5389     case ParsedAttr::AT_CFReturnsNotRetained:
5390       ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
5391       break;
5392     }
5393     S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
5394         << AL.getRange() << AL << ExpectedDeclKind;
5395     return;
5396   }
5397 
5398   bool TypeOK;
5399   bool Cf;
5400   unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
5401   switch (AL.getKind()) {
5402   default: llvm_unreachable("invalid ownership attribute");
5403   case ParsedAttr::AT_NSReturnsRetained:
5404     TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
5405     Cf = false;
5406     break;
5407 
5408   case ParsedAttr::AT_NSReturnsAutoreleased:
5409   case ParsedAttr::AT_NSReturnsNotRetained:
5410     TypeOK = isValidSubjectOfNSAttribute(ReturnType);
5411     Cf = false;
5412     break;
5413 
5414   case ParsedAttr::AT_CFReturnsRetained:
5415   case ParsedAttr::AT_CFReturnsNotRetained:
5416     TypeOK = isValidSubjectOfCFAttribute(ReturnType);
5417     Cf = true;
5418     break;
5419 
5420   case ParsedAttr::AT_OSReturnsRetained:
5421   case ParsedAttr::AT_OSReturnsNotRetained:
5422     TypeOK = isValidSubjectOfOSAttribute(ReturnType);
5423     Cf = true;
5424     ParmDiagID = 3; // Pointer-to-OSObject-pointer
5425     break;
5426   }
5427 
5428   if (!TypeOK) {
5429     if (AL.isUsedAsTypeAttr())
5430       return;
5431 
5432     if (isa<ParmVarDecl>(D)) {
5433       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5434           << AL << ParmDiagID << AL.getRange();
5435     } else {
5436       // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
5437       enum : unsigned {
5438         Function,
5439         Method,
5440         Property
5441       } SubjectKind = Function;
5442       if (isa<ObjCMethodDecl>(D))
5443         SubjectKind = Method;
5444       else if (isa<ObjCPropertyDecl>(D))
5445         SubjectKind = Property;
5446       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5447           << AL << SubjectKind << Cf << AL.getRange();
5448     }
5449     return;
5450   }
5451 
5452   switch (AL.getKind()) {
5453     default:
5454       llvm_unreachable("invalid ownership attribute");
5455     case ParsedAttr::AT_NSReturnsAutoreleased:
5456       handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
5457       return;
5458     case ParsedAttr::AT_CFReturnsNotRetained:
5459       handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
5460       return;
5461     case ParsedAttr::AT_NSReturnsNotRetained:
5462       handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
5463       return;
5464     case ParsedAttr::AT_CFReturnsRetained:
5465       handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
5466       return;
5467     case ParsedAttr::AT_NSReturnsRetained:
5468       handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
5469       return;
5470     case ParsedAttr::AT_OSReturnsRetained:
5471       handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5472       return;
5473     case ParsedAttr::AT_OSReturnsNotRetained:
5474       handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5475       return;
5476   };
5477 }
5478 
5479 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5480                                               const ParsedAttr &Attrs) {
5481   const int EP_ObjCMethod = 1;
5482   const int EP_ObjCProperty = 2;
5483 
5484   SourceLocation loc = Attrs.getLoc();
5485   QualType resultType;
5486   if (isa<ObjCMethodDecl>(D))
5487     resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5488   else
5489     resultType = cast<ObjCPropertyDecl>(D)->getType();
5490 
5491   if (!resultType->isReferenceType() &&
5492       (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5493     S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5494         << SourceRange(loc) << Attrs
5495         << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5496         << /*non-retainable pointer*/ 2;
5497 
5498     // Drop the attribute.
5499     return;
5500   }
5501 
5502   D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
5503 }
5504 
5505 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5506                                         const ParsedAttr &Attrs) {
5507   const auto *Method = cast<ObjCMethodDecl>(D);
5508 
5509   const DeclContext *DC = Method->getDeclContext();
5510   if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5511     S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5512                                                                       << 0;
5513     S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5514     return;
5515   }
5516   if (Method->getMethodFamily() == OMF_dealloc) {
5517     S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5518                                                                       << 1;
5519     return;
5520   }
5521 
5522   D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
5523 }
5524 
5525 static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &AL) {
5526   auto *E = AL.getArgAsExpr(0);
5527   auto Loc = E ? E->getBeginLoc() : AL.getLoc();
5528 
5529   auto *DRE = dyn_cast<DeclRefExpr>(AL.getArgAsExpr(0));
5530   if (!DRE) {
5531     S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
5532     return;
5533   }
5534 
5535   auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
5536   if (!VD) {
5537     S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 1 << DRE->getDecl();
5538     return;
5539   }
5540 
5541   if (!isNSStringType(VD->getType(), S.Context) &&
5542       !isCFStringType(VD->getType(), S.Context)) {
5543     S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD;
5544     return;
5545   }
5546 
5547   D->addAttr(::new (S.Context) NSErrorDomainAttr(S.Context, AL, VD));
5548 }
5549 
5550 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5551   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5552 
5553   if (!Parm) {
5554     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5555     return;
5556   }
5557 
5558   // Typedefs only allow objc_bridge(id) and have some additional checking.
5559   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5560     if (!Parm->Ident->isStr("id")) {
5561       S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5562       return;
5563     }
5564 
5565     // Only allow 'cv void *'.
5566     QualType T = TD->getUnderlyingType();
5567     if (!T->isVoidPointerType()) {
5568       S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5569       return;
5570     }
5571   }
5572 
5573   D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
5574 }
5575 
5576 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5577                                         const ParsedAttr &AL) {
5578   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5579 
5580   if (!Parm) {
5581     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5582     return;
5583   }
5584 
5585   D->addAttr(::new (S.Context)
5586                  ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
5587 }
5588 
5589 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5590                                         const ParsedAttr &AL) {
5591   IdentifierInfo *RelatedClass =
5592       AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5593   if (!RelatedClass) {
5594     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5595     return;
5596   }
5597   IdentifierInfo *ClassMethod =
5598     AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5599   IdentifierInfo *InstanceMethod =
5600     AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5601   D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
5602       S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
5603 }
5604 
5605 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5606                                             const ParsedAttr &AL) {
5607   DeclContext *Ctx = D->getDeclContext();
5608 
5609   // This attribute can only be applied to methods in interfaces or class
5610   // extensions.
5611   if (!isa<ObjCInterfaceDecl>(Ctx) &&
5612       !(isa<ObjCCategoryDecl>(Ctx) &&
5613         cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5614     S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5615     return;
5616   }
5617 
5618   ObjCInterfaceDecl *IFace;
5619   if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5620     IFace = CatDecl->getClassInterface();
5621   else
5622     IFace = cast<ObjCInterfaceDecl>(Ctx);
5623 
5624   if (!IFace)
5625     return;
5626 
5627   IFace->setHasDesignatedInitializers();
5628   D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
5629 }
5630 
5631 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5632   StringRef MetaDataName;
5633   if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5634     return;
5635   D->addAttr(::new (S.Context)
5636                  ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
5637 }
5638 
5639 // When a user wants to use objc_boxable with a union or struct
5640 // but they don't have access to the declaration (legacy/third-party code)
5641 // then they can 'enable' this feature with a typedef:
5642 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5643 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5644   bool notify = false;
5645 
5646   auto *RD = dyn_cast<RecordDecl>(D);
5647   if (RD && RD->getDefinition()) {
5648     RD = RD->getDefinition();
5649     notify = true;
5650   }
5651 
5652   if (RD) {
5653     ObjCBoxableAttr *BoxableAttr =
5654         ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
5655     RD->addAttr(BoxableAttr);
5656     if (notify) {
5657       // we need to notify ASTReader/ASTWriter about
5658       // modification of existing declaration
5659       if (ASTMutationListener *L = S.getASTMutationListener())
5660         L->AddedAttributeToRecord(BoxableAttr, RD);
5661     }
5662   }
5663 }
5664 
5665 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5666   if (hasDeclarator(D)) return;
5667 
5668   S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5669       << AL.getRange() << AL << ExpectedVariable;
5670 }
5671 
5672 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5673                                           const ParsedAttr &AL) {
5674   const auto *VD = cast<ValueDecl>(D);
5675   QualType QT = VD->getType();
5676 
5677   if (!QT->isDependentType() &&
5678       !QT->isObjCLifetimeType()) {
5679     S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5680       << QT;
5681     return;
5682   }
5683 
5684   Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5685 
5686   // If we have no lifetime yet, check the lifetime we're presumably
5687   // going to infer.
5688   if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5689     Lifetime = QT->getObjCARCImplicitLifetime();
5690 
5691   switch (Lifetime) {
5692   case Qualifiers::OCL_None:
5693     assert(QT->isDependentType() &&
5694            "didn't infer lifetime for non-dependent type?");
5695     break;
5696 
5697   case Qualifiers::OCL_Weak:   // meaningful
5698   case Qualifiers::OCL_Strong: // meaningful
5699     break;
5700 
5701   case Qualifiers::OCL_ExplicitNone:
5702   case Qualifiers::OCL_Autoreleasing:
5703     S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5704         << (Lifetime == Qualifiers::OCL_Autoreleasing);
5705     break;
5706   }
5707 
5708   D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
5709 }
5710 
5711 static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5712   // Make sure that there is a string literal as the annotation's single
5713   // argument.
5714   StringRef Str;
5715   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
5716     return;
5717 
5718   D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str));
5719 }
5720 
5721 static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) {
5722   // Make sure that there is a string literal as the annotation's single
5723   // argument.
5724   StringRef BT;
5725   if (!S.checkStringLiteralArgumentAttr(AL, 0, BT))
5726     return;
5727 
5728   // Don't duplicate annotations that are already set.
5729   if (D->hasAttr<SwiftBridgeAttr>()) {
5730     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
5731     return;
5732   }
5733 
5734   D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT));
5735 }
5736 
5737 static bool isErrorParameter(Sema &S, QualType QT) {
5738   const auto *PT = QT->getAs<PointerType>();
5739   if (!PT)
5740     return false;
5741 
5742   QualType Pointee = PT->getPointeeType();
5743 
5744   // Check for NSError**.
5745   if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>())
5746     if (const auto *ID = OPT->getInterfaceDecl())
5747       if (ID->getIdentifier() == S.getNSErrorIdent())
5748         return true;
5749 
5750   // Check for CFError**.
5751   if (const auto *PT = Pointee->getAs<PointerType>())
5752     if (const auto *RT = PT->getPointeeType()->getAs<RecordType>())
5753       if (S.isCFError(RT->getDecl()))
5754         return true;
5755 
5756   return false;
5757 }
5758 
5759 static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) {
5760   auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
5761     for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
5762       if (isErrorParameter(S, getFunctionOrMethodParamType(D, I)))
5763         return true;
5764     }
5765 
5766     S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter)
5767         << AL << isa<ObjCMethodDecl>(D);
5768     return false;
5769   };
5770 
5771   auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
5772     // - C, ObjC, and block pointers are definitely okay.
5773     // - References are definitely not okay.
5774     // - nullptr_t is weird, but acceptable.
5775     QualType RT = getFunctionOrMethodResultType(D);
5776     if (RT->hasPointerRepresentation() && !RT->isReferenceType())
5777       return true;
5778 
5779     S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
5780         << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
5781         << /*pointer*/ 1;
5782     return false;
5783   };
5784 
5785   auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
5786     QualType RT = getFunctionOrMethodResultType(D);
5787     if (RT->isIntegralType(S.Context))
5788       return true;
5789 
5790     S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
5791         << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
5792         << /*integral*/ 0;
5793     return false;
5794   };
5795 
5796   if (D->isInvalidDecl())
5797     return;
5798 
5799   IdentifierLoc *Loc = AL.getArgAsIdent(0);
5800   SwiftErrorAttr::ConventionKind Convention;
5801   if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(),
5802                                                   Convention)) {
5803     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5804         << AL << Loc->Ident;
5805     return;
5806   }
5807 
5808   switch (Convention) {
5809   case SwiftErrorAttr::None:
5810     // No additional validation required.
5811     break;
5812 
5813   case SwiftErrorAttr::NonNullError:
5814     if (!hasErrorParameter(S, D, AL))
5815       return;
5816     break;
5817 
5818   case SwiftErrorAttr::NullResult:
5819     if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL))
5820       return;
5821     break;
5822 
5823   case SwiftErrorAttr::NonZeroResult:
5824   case SwiftErrorAttr::ZeroResult:
5825     if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL))
5826       return;
5827     break;
5828   }
5829 
5830   D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention));
5831 }
5832 
5833 // For a function, this will validate a compound Swift name, e.g.
5834 // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
5835 // the function will output the number of parameter names, and whether this is a
5836 // single-arg initializer.
5837 //
5838 // For a type, enum constant, property, or variable declaration, this will
5839 // validate either a simple identifier, or a qualified
5840 // <code>context.identifier</code> name.
5841 static bool
5842 validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc,
5843                           StringRef Name, unsigned &SwiftParamCount,
5844                           bool &IsSingleParamInit) {
5845   SwiftParamCount = 0;
5846   IsSingleParamInit = false;
5847 
5848   // Check whether this will be mapped to a getter or setter of a property.
5849   bool IsGetter = false, IsSetter = false;
5850   if (Name.startswith("getter:")) {
5851     IsGetter = true;
5852     Name = Name.substr(7);
5853   } else if (Name.startswith("setter:")) {
5854     IsSetter = true;
5855     Name = Name.substr(7);
5856   }
5857 
5858   if (Name.back() != ')') {
5859     S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
5860     return false;
5861   }
5862 
5863   bool IsMember = false;
5864   StringRef ContextName, BaseName, Parameters;
5865 
5866   std::tie(BaseName, Parameters) = Name.split('(');
5867 
5868   // Split at the first '.', if it exists, which separates the context name
5869   // from the base name.
5870   std::tie(ContextName, BaseName) = BaseName.split('.');
5871   if (BaseName.empty()) {
5872     BaseName = ContextName;
5873     ContextName = StringRef();
5874   } else if (ContextName.empty() || !isValidIdentifier(ContextName)) {
5875     S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
5876         << AL << /*context*/ 1;
5877     return false;
5878   } else {
5879     IsMember = true;
5880   }
5881 
5882   if (!isValidIdentifier(BaseName) || BaseName == "_") {
5883     S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
5884         << AL << /*basename*/ 0;
5885     return false;
5886   }
5887 
5888   bool IsSubscript = BaseName == "subscript";
5889   // A subscript accessor must be a getter or setter.
5890   if (IsSubscript && !IsGetter && !IsSetter) {
5891     S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
5892         << AL << /* getter or setter */ 0;
5893     return false;
5894   }
5895 
5896   if (Parameters.empty()) {
5897     S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL;
5898     return false;
5899   }
5900 
5901   assert(Parameters.back() == ')' && "expected ')'");
5902   Parameters = Parameters.drop_back(); // ')'
5903 
5904   if (Parameters.empty()) {
5905     // Setters and subscripts must have at least one parameter.
5906     if (IsSubscript) {
5907       S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
5908           << AL << /* have at least one parameter */1;
5909       return false;
5910     }
5911 
5912     if (IsSetter) {
5913       S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL;
5914       return false;
5915     }
5916 
5917     return true;
5918   }
5919 
5920   if (Parameters.back() != ':') {
5921     S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
5922     return false;
5923   }
5924 
5925   StringRef CurrentParam;
5926   llvm::Optional<unsigned> SelfLocation;
5927   unsigned NewValueCount = 0;
5928   llvm::Optional<unsigned> NewValueLocation;
5929   do {
5930     std::tie(CurrentParam, Parameters) = Parameters.split(':');
5931 
5932     if (!isValidIdentifier(CurrentParam)) {
5933       S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
5934           << AL << /*parameter*/2;
5935       return false;
5936     }
5937 
5938     if (IsMember && CurrentParam == "self") {
5939       // "self" indicates the "self" argument for a member.
5940 
5941       // More than one "self"?
5942       if (SelfLocation) {
5943         S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL;
5944         return false;
5945       }
5946 
5947       // The "self" location is the current parameter.
5948       SelfLocation = SwiftParamCount;
5949     } else if (CurrentParam == "newValue") {
5950       // "newValue" indicates the "newValue" argument for a setter.
5951 
5952       // There should only be one 'newValue', but it's only significant for
5953       // subscript accessors, so don't error right away.
5954       ++NewValueCount;
5955 
5956       NewValueLocation = SwiftParamCount;
5957     }
5958 
5959     ++SwiftParamCount;
5960   } while (!Parameters.empty());
5961 
5962   // Only instance subscripts are currently supported.
5963   if (IsSubscript && !SelfLocation) {
5964     S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
5965         << AL << /*have a 'self:' parameter*/2;
5966     return false;
5967   }
5968 
5969   IsSingleParamInit =
5970         SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_";
5971 
5972   // Check the number of parameters for a getter/setter.
5973   if (IsGetter || IsSetter) {
5974     // Setters have one parameter for the new value.
5975     unsigned NumExpectedParams = IsGetter ? 0 : 1;
5976     unsigned ParamDiag =
5977         IsGetter ? diag::warn_attr_swift_name_getter_parameters
5978                  : diag::warn_attr_swift_name_setter_parameters;
5979 
5980     // Instance methods have one parameter for "self".
5981     if (SelfLocation)
5982       ++NumExpectedParams;
5983 
5984     // Subscripts may have additional parameters beyond the expected params for
5985     // the index.
5986     if (IsSubscript) {
5987       if (SwiftParamCount < NumExpectedParams) {
5988         S.Diag(Loc, ParamDiag) << AL;
5989         return false;
5990       }
5991 
5992       // A subscript setter must explicitly label its newValue parameter to
5993       // distinguish it from index parameters.
5994       if (IsSetter) {
5995         if (!NewValueLocation) {
5996           S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue)
5997               << AL;
5998           return false;
5999         }
6000         if (NewValueCount > 1) {
6001           S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues)
6002               << AL;
6003           return false;
6004         }
6005       } else {
6006         // Subscript getters should have no 'newValue:' parameter.
6007         if (NewValueLocation) {
6008           S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue)
6009               << AL;
6010           return false;
6011         }
6012       }
6013     } else {
6014       // Property accessors must have exactly the number of expected params.
6015       if (SwiftParamCount != NumExpectedParams) {
6016         S.Diag(Loc, ParamDiag) << AL;
6017         return false;
6018       }
6019     }
6020   }
6021 
6022   return true;
6023 }
6024 
6025 bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
6026                              const ParsedAttr &AL, bool IsAsync) {
6027   if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
6028     ArrayRef<ParmVarDecl*> Params;
6029     unsigned ParamCount;
6030 
6031     if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) {
6032       ParamCount = Method->getSelector().getNumArgs();
6033       Params = Method->parameters().slice(0, ParamCount);
6034     } else {
6035       const auto *F = cast<FunctionDecl>(D);
6036 
6037       ParamCount = F->getNumParams();
6038       Params = F->parameters();
6039 
6040       if (!F->hasWrittenPrototype()) {
6041         Diag(Loc, diag::warn_attribute_wrong_decl_type) << AL
6042             << ExpectedFunctionWithProtoType;
6043         return false;
6044       }
6045     }
6046 
6047     // The async name drops the last callback parameter.
6048     if (IsAsync) {
6049       if (ParamCount == 0) {
6050         Diag(Loc, diag::warn_attr_swift_name_decl_missing_params)
6051             << AL << isa<ObjCMethodDecl>(D);
6052         return false;
6053       }
6054       ParamCount -= 1;
6055     }
6056 
6057     unsigned SwiftParamCount;
6058     bool IsSingleParamInit;
6059     if (!validateSwiftFunctionName(*this, AL, Loc, Name,
6060                                    SwiftParamCount, IsSingleParamInit))
6061       return false;
6062 
6063     bool ParamCountValid;
6064     if (SwiftParamCount == ParamCount) {
6065       ParamCountValid = true;
6066     } else if (SwiftParamCount > ParamCount) {
6067       ParamCountValid = IsSingleParamInit && ParamCount == 0;
6068     } else {
6069       // We have fewer Swift parameters than Objective-C parameters, but that
6070       // might be because we've transformed some of them. Check for potential
6071       // "out" parameters and err on the side of not warning.
6072       unsigned MaybeOutParamCount =
6073           std::count_if(Params.begin(), Params.end(),
6074                         [](const ParmVarDecl *Param) -> bool {
6075         QualType ParamTy = Param->getType();
6076         if (ParamTy->isReferenceType() || ParamTy->isPointerType())
6077           return !ParamTy->getPointeeType().isConstQualified();
6078         return false;
6079       });
6080 
6081       ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount;
6082     }
6083 
6084     if (!ParamCountValid) {
6085       Diag(Loc, diag::warn_attr_swift_name_num_params)
6086           << (SwiftParamCount > ParamCount) << AL << ParamCount
6087           << SwiftParamCount;
6088       return false;
6089     }
6090   } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) ||
6091               isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) ||
6092               isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) ||
6093               isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) &&
6094              !IsAsync) {
6095     StringRef ContextName, BaseName;
6096 
6097     std::tie(ContextName, BaseName) = Name.split('.');
6098     if (BaseName.empty()) {
6099       BaseName = ContextName;
6100       ContextName = StringRef();
6101     } else if (!isValidIdentifier(ContextName)) {
6102       Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6103           << /*context*/1;
6104       return false;
6105     }
6106 
6107     if (!isValidIdentifier(BaseName)) {
6108       Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6109           << /*basename*/0;
6110       return false;
6111     }
6112   } else {
6113     Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL;
6114     return false;
6115   }
6116   return true;
6117 }
6118 
6119 static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) {
6120   StringRef Name;
6121   SourceLocation Loc;
6122   if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6123     return;
6124 
6125   if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false))
6126     return;
6127 
6128   D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name));
6129 }
6130 
6131 static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) {
6132   StringRef Name;
6133   SourceLocation Loc;
6134   if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6135     return;
6136 
6137   if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true))
6138     return;
6139 
6140   D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name));
6141 }
6142 
6143 static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) {
6144   // Make sure that there is an identifier as the annotation's single argument.
6145   if (!checkAttributeNumArgs(S, AL, 1))
6146     return;
6147 
6148   if (!AL.isArgIdent(0)) {
6149     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6150         << AL << AANT_ArgumentIdentifier;
6151     return;
6152   }
6153 
6154   SwiftNewTypeAttr::NewtypeKind Kind;
6155   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6156   if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) {
6157     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
6158     return;
6159   }
6160 
6161   if (!isa<TypedefNameDecl>(D)) {
6162     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
6163         << AL << "typedefs";
6164     return;
6165   }
6166 
6167   D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind));
6168 }
6169 
6170 static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6171   if (!AL.isArgIdent(0)) {
6172     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
6173         << AL << 1 << AANT_ArgumentIdentifier;
6174     return;
6175   }
6176 
6177   SwiftAsyncAttr::Kind Kind;
6178   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6179   if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) {
6180     S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II;
6181     return;
6182   }
6183 
6184   ParamIdx Idx;
6185   if (Kind == SwiftAsyncAttr::None) {
6186     // If this is 'none', then there shouldn't be any additional arguments.
6187     if (!checkAttributeNumArgs(S, AL, 1))
6188       return;
6189   } else {
6190     // Non-none swift_async requires a completion handler index argument.
6191     if (!checkAttributeNumArgs(S, AL, 2))
6192       return;
6193 
6194     Expr *HandlerIdx = AL.getArgAsExpr(1);
6195     if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx))
6196       return;
6197 
6198     const ParmVarDecl *CompletionBlock =
6199         getFunctionOrMethodParam(D, Idx.getASTIndex());
6200     QualType CompletionBlockType = CompletionBlock->getType();
6201     if (!CompletionBlockType->isBlockPointerType()) {
6202       S.Diag(CompletionBlock->getLocation(),
6203              diag::err_swift_async_bad_block_type)
6204           << CompletionBlock->getType();
6205       return;
6206     }
6207     QualType BlockTy =
6208         CompletionBlockType->getAs<BlockPointerType>()->getPointeeType();
6209     if (!BlockTy->getAs<FunctionType>()->getReturnType()->isVoidType()) {
6210       S.Diag(CompletionBlock->getLocation(),
6211              diag::err_swift_async_bad_block_type)
6212           << CompletionBlock->getType();
6213       return;
6214     }
6215   }
6216 
6217   D->addAttr(::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx));
6218 }
6219 
6220 //===----------------------------------------------------------------------===//
6221 // Microsoft specific attribute handlers.
6222 //===----------------------------------------------------------------------===//
6223 
6224 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
6225                               StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
6226   if (const auto *UA = D->getAttr<UuidAttr>()) {
6227     if (declaresSameEntity(UA->getGuidDecl(), GuidDecl))
6228       return nullptr;
6229     if (!UA->getGuid().empty()) {
6230       Diag(UA->getLocation(), diag::err_mismatched_uuid);
6231       Diag(CI.getLoc(), diag::note_previous_uuid);
6232       D->dropAttr<UuidAttr>();
6233     }
6234   }
6235 
6236   return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
6237 }
6238 
6239 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6240   if (!S.LangOpts.CPlusPlus) {
6241     S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
6242         << AL << AttributeLangSupport::C;
6243     return;
6244   }
6245 
6246   StringRef OrigStrRef;
6247   SourceLocation LiteralLoc;
6248   if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc))
6249     return;
6250 
6251   // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
6252   // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
6253   StringRef StrRef = OrigStrRef;
6254   if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
6255     StrRef = StrRef.drop_front().drop_back();
6256 
6257   // Validate GUID length.
6258   if (StrRef.size() != 36) {
6259     S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
6260     return;
6261   }
6262 
6263   for (unsigned i = 0; i < 36; ++i) {
6264     if (i == 8 || i == 13 || i == 18 || i == 23) {
6265       if (StrRef[i] != '-') {
6266         S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
6267         return;
6268       }
6269     } else if (!isHexDigit(StrRef[i])) {
6270       S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
6271       return;
6272     }
6273   }
6274 
6275   // Convert to our parsed format and canonicalize.
6276   MSGuidDecl::Parts Parsed;
6277   StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1);
6278   StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2);
6279   StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3);
6280   for (unsigned i = 0; i != 8; ++i)
6281     StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2)
6282         .getAsInteger(16, Parsed.Part4And5[i]);
6283   MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed);
6284 
6285   // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
6286   // the only thing in the [] list, the [] too), and add an insertion of
6287   // __declspec(uuid(...)).  But sadly, neither the SourceLocs of the commas
6288   // separating attributes nor of the [ and the ] are in the AST.
6289   // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
6290   // on cfe-dev.
6291   if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
6292     S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
6293 
6294   UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid);
6295   if (UA)
6296     D->addAttr(UA);
6297 }
6298 
6299 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6300   if (!S.LangOpts.CPlusPlus) {
6301     S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
6302         << AL << AttributeLangSupport::C;
6303     return;
6304   }
6305   MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
6306       D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
6307   if (IA) {
6308     D->addAttr(IA);
6309     S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
6310   }
6311 }
6312 
6313 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6314   const auto *VD = cast<VarDecl>(D);
6315   if (!S.Context.getTargetInfo().isTLSSupported()) {
6316     S.Diag(AL.getLoc(), diag::err_thread_unsupported);
6317     return;
6318   }
6319   if (VD->getTSCSpec() != TSCS_unspecified) {
6320     S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
6321     return;
6322   }
6323   if (VD->hasLocalStorage()) {
6324     S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
6325     return;
6326   }
6327   D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
6328 }
6329 
6330 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6331   SmallVector<StringRef, 4> Tags;
6332   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6333     StringRef Tag;
6334     if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
6335       return;
6336     Tags.push_back(Tag);
6337   }
6338 
6339   if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
6340     if (!NS->isInline()) {
6341       S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
6342       return;
6343     }
6344     if (NS->isAnonymousNamespace()) {
6345       S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
6346       return;
6347     }
6348     if (AL.getNumArgs() == 0)
6349       Tags.push_back(NS->getName());
6350   } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6351     return;
6352 
6353   // Store tags sorted and without duplicates.
6354   llvm::sort(Tags);
6355   Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
6356 
6357   D->addAttr(::new (S.Context)
6358                  AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
6359 }
6360 
6361 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6362   // Check the attribute arguments.
6363   if (AL.getNumArgs() > 1) {
6364     S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
6365     return;
6366   }
6367 
6368   StringRef Str;
6369   SourceLocation ArgLoc;
6370 
6371   if (AL.getNumArgs() == 0)
6372     Str = "";
6373   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6374     return;
6375 
6376   ARMInterruptAttr::InterruptType Kind;
6377   if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
6378     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
6379                                                                  << ArgLoc;
6380     return;
6381   }
6382 
6383   D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
6384 }
6385 
6386 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6387   // MSP430 'interrupt' attribute is applied to
6388   // a function with no parameters and void return type.
6389   if (!isFunctionOrMethod(D)) {
6390     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6391         << "'interrupt'" << ExpectedFunctionOrMethod;
6392     return;
6393   }
6394 
6395   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
6396     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6397         << /*MSP430*/ 1 << 0;
6398     return;
6399   }
6400 
6401   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6402     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6403         << /*MSP430*/ 1 << 1;
6404     return;
6405   }
6406 
6407   // The attribute takes one integer argument.
6408   if (!checkAttributeNumArgs(S, AL, 1))
6409     return;
6410 
6411   if (!AL.isArgExpr(0)) {
6412     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6413         << AL << AANT_ArgumentIntegerConstant;
6414     return;
6415   }
6416 
6417   Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
6418   Optional<llvm::APSInt> NumParams = llvm::APSInt(32);
6419   if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) {
6420     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6421         << AL << AANT_ArgumentIntegerConstant
6422         << NumParamsExpr->getSourceRange();
6423     return;
6424   }
6425   // The argument should be in range 0..63.
6426   unsigned Num = NumParams->getLimitedValue(255);
6427   if (Num > 63) {
6428     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
6429         << AL << (int)NumParams->getSExtValue()
6430         << NumParamsExpr->getSourceRange();
6431     return;
6432   }
6433 
6434   D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
6435   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6436 }
6437 
6438 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6439   // Only one optional argument permitted.
6440   if (AL.getNumArgs() > 1) {
6441     S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
6442     return;
6443   }
6444 
6445   StringRef Str;
6446   SourceLocation ArgLoc;
6447 
6448   if (AL.getNumArgs() == 0)
6449     Str = "";
6450   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6451     return;
6452 
6453   // Semantic checks for a function with the 'interrupt' attribute for MIPS:
6454   // a) Must be a function.
6455   // b) Must have no parameters.
6456   // c) Must have the 'void' return type.
6457   // d) Cannot have the 'mips16' attribute, as that instruction set
6458   //    lacks the 'eret' instruction.
6459   // e) The attribute itself must either have no argument or one of the
6460   //    valid interrupt types, see [MipsInterruptDocs].
6461 
6462   if (!isFunctionOrMethod(D)) {
6463     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6464         << "'interrupt'" << ExpectedFunctionOrMethod;
6465     return;
6466   }
6467 
6468   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
6469     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6470         << /*MIPS*/ 0 << 0;
6471     return;
6472   }
6473 
6474   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6475     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6476         << /*MIPS*/ 0 << 1;
6477     return;
6478   }
6479 
6480   if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
6481     return;
6482 
6483   MipsInterruptAttr::InterruptType Kind;
6484   if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
6485     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6486         << AL << "'" + std::string(Str) + "'";
6487     return;
6488   }
6489 
6490   D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
6491 }
6492 
6493 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6494   // Semantic checks for a function with the 'interrupt' attribute.
6495   // a) Must be a function.
6496   // b) Must have the 'void' return type.
6497   // c) Must take 1 or 2 arguments.
6498   // d) The 1st argument must be a pointer.
6499   // e) The 2nd argument (if any) must be an unsigned integer.
6500   if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
6501       CXXMethodDecl::isStaticOverloadedOperator(
6502           cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
6503     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
6504         << AL << ExpectedFunctionWithProtoType;
6505     return;
6506   }
6507   // Interrupt handler must have void return type.
6508   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6509     S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
6510            diag::err_anyx86_interrupt_attribute)
6511         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6512                 ? 0
6513                 : 1)
6514         << 0;
6515     return;
6516   }
6517   // Interrupt handler must have 1 or 2 parameters.
6518   unsigned NumParams = getFunctionOrMethodNumParams(D);
6519   if (NumParams < 1 || NumParams > 2) {
6520     S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
6521         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6522                 ? 0
6523                 : 1)
6524         << 1;
6525     return;
6526   }
6527   // The first argument must be a pointer.
6528   if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
6529     S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
6530            diag::err_anyx86_interrupt_attribute)
6531         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6532                 ? 0
6533                 : 1)
6534         << 2;
6535     return;
6536   }
6537   // The second argument, if present, must be an unsigned integer.
6538   unsigned TypeSize =
6539       S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
6540           ? 64
6541           : 32;
6542   if (NumParams == 2 &&
6543       (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
6544        S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
6545     S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
6546            diag::err_anyx86_interrupt_attribute)
6547         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6548                 ? 0
6549                 : 1)
6550         << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
6551     return;
6552   }
6553   D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
6554   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6555 }
6556 
6557 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6558   if (!isFunctionOrMethod(D)) {
6559     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6560         << "'interrupt'" << ExpectedFunction;
6561     return;
6562   }
6563 
6564   if (!checkAttributeNumArgs(S, AL, 0))
6565     return;
6566 
6567   handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
6568 }
6569 
6570 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6571   if (!isFunctionOrMethod(D)) {
6572     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6573         << "'signal'" << ExpectedFunction;
6574     return;
6575   }
6576 
6577   if (!checkAttributeNumArgs(S, AL, 0))
6578     return;
6579 
6580   handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
6581 }
6582 
6583 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
6584   // Add preserve_access_index attribute to all fields and inner records.
6585   for (auto D : RD->decls()) {
6586     if (D->hasAttr<BPFPreserveAccessIndexAttr>())
6587       continue;
6588 
6589     D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
6590     if (auto *Rec = dyn_cast<RecordDecl>(D))
6591       handleBPFPreserveAIRecord(S, Rec);
6592   }
6593 }
6594 
6595 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
6596     const ParsedAttr &AL) {
6597   auto *Rec = cast<RecordDecl>(D);
6598   handleBPFPreserveAIRecord(S, Rec);
6599   Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
6600 }
6601 
6602 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6603   if (!isFunctionOrMethod(D)) {
6604     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6605         << "'export_name'" << ExpectedFunction;
6606     return;
6607   }
6608 
6609   auto *FD = cast<FunctionDecl>(D);
6610   if (FD->isThisDeclarationADefinition()) {
6611     S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
6612     return;
6613   }
6614 
6615   StringRef Str;
6616   SourceLocation ArgLoc;
6617   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6618     return;
6619 
6620   D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
6621   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6622 }
6623 
6624 WebAssemblyImportModuleAttr *
6625 Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) {
6626   auto *FD = cast<FunctionDecl>(D);
6627 
6628   if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
6629     if (ExistingAttr->getImportModule() == AL.getImportModule())
6630       return nullptr;
6631     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0
6632       << ExistingAttr->getImportModule() << AL.getImportModule();
6633     Diag(AL.getLoc(), diag::note_previous_attribute);
6634     return nullptr;
6635   }
6636   if (FD->hasBody()) {
6637     Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
6638     return nullptr;
6639   }
6640   return ::new (Context) WebAssemblyImportModuleAttr(Context, AL,
6641                                                      AL.getImportModule());
6642 }
6643 
6644 WebAssemblyImportNameAttr *
6645 Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) {
6646   auto *FD = cast<FunctionDecl>(D);
6647 
6648   if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) {
6649     if (ExistingAttr->getImportName() == AL.getImportName())
6650       return nullptr;
6651     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1
6652       << ExistingAttr->getImportName() << AL.getImportName();
6653     Diag(AL.getLoc(), diag::note_previous_attribute);
6654     return nullptr;
6655   }
6656   if (FD->hasBody()) {
6657     Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
6658     return nullptr;
6659   }
6660   return ::new (Context) WebAssemblyImportNameAttr(Context, AL,
6661                                                    AL.getImportName());
6662 }
6663 
6664 static void
6665 handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6666   auto *FD = cast<FunctionDecl>(D);
6667 
6668   StringRef Str;
6669   SourceLocation ArgLoc;
6670   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6671     return;
6672   if (FD->hasBody()) {
6673     S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
6674     return;
6675   }
6676 
6677   FD->addAttr(::new (S.Context)
6678                   WebAssemblyImportModuleAttr(S.Context, AL, Str));
6679 }
6680 
6681 static void
6682 handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6683   auto *FD = cast<FunctionDecl>(D);
6684 
6685   StringRef Str;
6686   SourceLocation ArgLoc;
6687   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6688     return;
6689   if (FD->hasBody()) {
6690     S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
6691     return;
6692   }
6693 
6694   FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
6695 }
6696 
6697 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
6698                                      const ParsedAttr &AL) {
6699   // Warn about repeated attributes.
6700   if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
6701     S.Diag(AL.getRange().getBegin(),
6702       diag::warn_riscv_repeated_interrupt_attribute);
6703     S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
6704     return;
6705   }
6706 
6707   // Check the attribute argument. Argument is optional.
6708   if (!checkAttributeAtMostNumArgs(S, AL, 1))
6709     return;
6710 
6711   StringRef Str;
6712   SourceLocation ArgLoc;
6713 
6714   // 'machine'is the default interrupt mode.
6715   if (AL.getNumArgs() == 0)
6716     Str = "machine";
6717   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6718     return;
6719 
6720   // Semantic checks for a function with the 'interrupt' attribute:
6721   // - Must be a function.
6722   // - Must have no parameters.
6723   // - Must have the 'void' return type.
6724   // - The attribute itself must either have no argument or one of the
6725   //   valid interrupt types, see [RISCVInterruptDocs].
6726 
6727   if (D->getFunctionType() == nullptr) {
6728     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6729       << "'interrupt'" << ExpectedFunction;
6730     return;
6731   }
6732 
6733   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
6734     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6735       << /*RISC-V*/ 2 << 0;
6736     return;
6737   }
6738 
6739   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6740     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6741       << /*RISC-V*/ 2 << 1;
6742     return;
6743   }
6744 
6745   RISCVInterruptAttr::InterruptType Kind;
6746   if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
6747     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
6748                                                                  << ArgLoc;
6749     return;
6750   }
6751 
6752   D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
6753 }
6754 
6755 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6756   // Dispatch the interrupt attribute based on the current target.
6757   switch (S.Context.getTargetInfo().getTriple().getArch()) {
6758   case llvm::Triple::msp430:
6759     handleMSP430InterruptAttr(S, D, AL);
6760     break;
6761   case llvm::Triple::mipsel:
6762   case llvm::Triple::mips:
6763     handleMipsInterruptAttr(S, D, AL);
6764     break;
6765   case llvm::Triple::x86:
6766   case llvm::Triple::x86_64:
6767     handleAnyX86InterruptAttr(S, D, AL);
6768     break;
6769   case llvm::Triple::avr:
6770     handleAVRInterruptAttr(S, D, AL);
6771     break;
6772   case llvm::Triple::riscv32:
6773   case llvm::Triple::riscv64:
6774     handleRISCVInterruptAttr(S, D, AL);
6775     break;
6776   default:
6777     handleARMInterruptAttr(S, D, AL);
6778     break;
6779   }
6780 }
6781 
6782 static bool
6783 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
6784                                       const AMDGPUFlatWorkGroupSizeAttr &Attr) {
6785   // Accept template arguments for now as they depend on something else.
6786   // We'll get to check them when they eventually get instantiated.
6787   if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
6788     return false;
6789 
6790   uint32_t Min = 0;
6791   if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
6792     return true;
6793 
6794   uint32_t Max = 0;
6795   if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
6796     return true;
6797 
6798   if (Min == 0 && Max != 0) {
6799     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6800         << &Attr << 0;
6801     return true;
6802   }
6803   if (Min > Max) {
6804     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6805         << &Attr << 1;
6806     return true;
6807   }
6808 
6809   return false;
6810 }
6811 
6812 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
6813                                           const AttributeCommonInfo &CI,
6814                                           Expr *MinExpr, Expr *MaxExpr) {
6815   AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
6816 
6817   if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
6818     return;
6819 
6820   D->addAttr(::new (Context)
6821                  AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr));
6822 }
6823 
6824 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
6825                                               const ParsedAttr &AL) {
6826   Expr *MinExpr = AL.getArgAsExpr(0);
6827   Expr *MaxExpr = AL.getArgAsExpr(1);
6828 
6829   S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
6830 }
6831 
6832 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
6833                                            Expr *MaxExpr,
6834                                            const AMDGPUWavesPerEUAttr &Attr) {
6835   if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
6836       (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
6837     return true;
6838 
6839   // Accept template arguments for now as they depend on something else.
6840   // We'll get to check them when they eventually get instantiated.
6841   if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
6842     return false;
6843 
6844   uint32_t Min = 0;
6845   if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
6846     return true;
6847 
6848   uint32_t Max = 0;
6849   if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
6850     return true;
6851 
6852   if (Min == 0 && Max != 0) {
6853     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6854         << &Attr << 0;
6855     return true;
6856   }
6857   if (Max != 0 && Min > Max) {
6858     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
6859         << &Attr << 1;
6860     return true;
6861   }
6862 
6863   return false;
6864 }
6865 
6866 void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
6867                                    Expr *MinExpr, Expr *MaxExpr) {
6868   AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
6869 
6870   if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
6871     return;
6872 
6873   D->addAttr(::new (Context)
6874                  AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr));
6875 }
6876 
6877 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6878   if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
6879       !checkAttributeAtMostNumArgs(S, AL, 2))
6880     return;
6881 
6882   Expr *MinExpr = AL.getArgAsExpr(0);
6883   Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
6884 
6885   S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
6886 }
6887 
6888 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6889   uint32_t NumSGPR = 0;
6890   Expr *NumSGPRExpr = AL.getArgAsExpr(0);
6891   if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
6892     return;
6893 
6894   D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
6895 }
6896 
6897 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6898   uint32_t NumVGPR = 0;
6899   Expr *NumVGPRExpr = AL.getArgAsExpr(0);
6900   if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
6901     return;
6902 
6903   D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
6904 }
6905 
6906 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
6907                                               const ParsedAttr &AL) {
6908   // If we try to apply it to a function pointer, don't warn, but don't
6909   // do anything, either. It doesn't matter anyway, because there's nothing
6910   // special about calling a force_align_arg_pointer function.
6911   const auto *VD = dyn_cast<ValueDecl>(D);
6912   if (VD && VD->getType()->isFunctionPointerType())
6913     return;
6914   // Also don't warn on function pointer typedefs.
6915   const auto *TD = dyn_cast<TypedefNameDecl>(D);
6916   if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
6917     TD->getUnderlyingType()->isFunctionType()))
6918     return;
6919   // Attribute can only be applied to function types.
6920   if (!isa<FunctionDecl>(D)) {
6921     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
6922         << AL << ExpectedFunction;
6923     return;
6924   }
6925 
6926   D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
6927 }
6928 
6929 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
6930   uint32_t Version;
6931   Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
6932   if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
6933     return;
6934 
6935   // TODO: Investigate what happens with the next major version of MSVC.
6936   if (Version != LangOptions::MSVC2015 / 100) {
6937     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
6938         << AL << Version << VersionExpr->getSourceRange();
6939     return;
6940   }
6941 
6942   // The attribute expects a "major" version number like 19, but new versions of
6943   // MSVC have moved to updating the "minor", or less significant numbers, so we
6944   // have to multiply by 100 now.
6945   Version *= 100;
6946 
6947   D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
6948 }
6949 
6950 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
6951                                         const AttributeCommonInfo &CI) {
6952   if (D->hasAttr<DLLExportAttr>()) {
6953     Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
6954     return nullptr;
6955   }
6956 
6957   if (D->hasAttr<DLLImportAttr>())
6958     return nullptr;
6959 
6960   return ::new (Context) DLLImportAttr(Context, CI);
6961 }
6962 
6963 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
6964                                         const AttributeCommonInfo &CI) {
6965   if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
6966     Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
6967     D->dropAttr<DLLImportAttr>();
6968   }
6969 
6970   if (D->hasAttr<DLLExportAttr>())
6971     return nullptr;
6972 
6973   return ::new (Context) DLLExportAttr(Context, CI);
6974 }
6975 
6976 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6977   if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
6978       (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
6979     S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
6980     return;
6981   }
6982 
6983   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
6984     if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
6985         !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
6986       // MinGW doesn't allow dllimport on inline functions.
6987       S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
6988           << A;
6989       return;
6990     }
6991   }
6992 
6993   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
6994     if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) &&
6995         MD->getParent()->isLambda()) {
6996       S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
6997       return;
6998     }
6999   }
7000 
7001   Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
7002                       ? (Attr *)S.mergeDLLExportAttr(D, A)
7003                       : (Attr *)S.mergeDLLImportAttr(D, A);
7004   if (NewAttr)
7005     D->addAttr(NewAttr);
7006 }
7007 
7008 MSInheritanceAttr *
7009 Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
7010                              bool BestCase,
7011                              MSInheritanceModel Model) {
7012   if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
7013     if (IA->getInheritanceModel() == Model)
7014       return nullptr;
7015     Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
7016         << 1 /*previous declaration*/;
7017     Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
7018     D->dropAttr<MSInheritanceAttr>();
7019   }
7020 
7021   auto *RD = cast<CXXRecordDecl>(D);
7022   if (RD->hasDefinition()) {
7023     if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
7024                                            Model)) {
7025       return nullptr;
7026     }
7027   } else {
7028     if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
7029       Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
7030           << 1 /*partial specialization*/;
7031       return nullptr;
7032     }
7033     if (RD->getDescribedClassTemplate()) {
7034       Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
7035           << 0 /*primary template*/;
7036       return nullptr;
7037     }
7038   }
7039 
7040   return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
7041 }
7042 
7043 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7044   // The capability attributes take a single string parameter for the name of
7045   // the capability they represent. The lockable attribute does not take any
7046   // parameters. However, semantically, both attributes represent the same
7047   // concept, and so they use the same semantic attribute. Eventually, the
7048   // lockable attribute will be removed.
7049   //
7050   // For backward compatibility, any capability which has no specified string
7051   // literal will be considered a "mutex."
7052   StringRef N("mutex");
7053   SourceLocation LiteralLoc;
7054   if (AL.getKind() == ParsedAttr::AT_Capability &&
7055       !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
7056     return;
7057 
7058   D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
7059 }
7060 
7061 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7062   SmallVector<Expr*, 1> Args;
7063   if (!checkLockFunAttrCommon(S, D, AL, Args))
7064     return;
7065 
7066   D->addAttr(::new (S.Context)
7067                  AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
7068 }
7069 
7070 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
7071                                         const ParsedAttr &AL) {
7072   SmallVector<Expr*, 1> Args;
7073   if (!checkLockFunAttrCommon(S, D, AL, Args))
7074     return;
7075 
7076   D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
7077                                                      Args.size()));
7078 }
7079 
7080 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
7081                                            const ParsedAttr &AL) {
7082   SmallVector<Expr*, 2> Args;
7083   if (!checkTryLockFunAttrCommon(S, D, AL, Args))
7084     return;
7085 
7086   D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
7087       S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
7088 }
7089 
7090 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
7091                                         const ParsedAttr &AL) {
7092   // Check that all arguments are lockable objects.
7093   SmallVector<Expr *, 1> Args;
7094   checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
7095 
7096   D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
7097                                                      Args.size()));
7098 }
7099 
7100 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
7101                                          const ParsedAttr &AL) {
7102   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
7103     return;
7104 
7105   // check that all arguments are lockable objects
7106   SmallVector<Expr*, 1> Args;
7107   checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
7108   if (Args.empty())
7109     return;
7110 
7111   RequiresCapabilityAttr *RCA = ::new (S.Context)
7112       RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
7113 
7114   D->addAttr(RCA);
7115 }
7116 
7117 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7118   if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
7119     if (NSD->isAnonymousNamespace()) {
7120       S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
7121       // Do not want to attach the attribute to the namespace because that will
7122       // cause confusing diagnostic reports for uses of declarations within the
7123       // namespace.
7124       return;
7125     }
7126   }
7127 
7128   // Handle the cases where the attribute has a text message.
7129   StringRef Str, Replacement;
7130   if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
7131       !S.checkStringLiteralArgumentAttr(AL, 0, Str))
7132     return;
7133 
7134   // Only support a single optional message for Declspec and CXX11.
7135   if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
7136     checkAttributeAtMostNumArgs(S, AL, 1);
7137   else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
7138            !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
7139     return;
7140 
7141   if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
7142     S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
7143 
7144   D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
7145 }
7146 
7147 static bool isGlobalVar(const Decl *D) {
7148   if (const auto *S = dyn_cast<VarDecl>(D))
7149     return S->hasGlobalStorage();
7150   return false;
7151 }
7152 
7153 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7154   if (!checkAttributeAtLeastNumArgs(S, AL, 1))
7155     return;
7156 
7157   std::vector<StringRef> Sanitizers;
7158 
7159   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
7160     StringRef SanitizerName;
7161     SourceLocation LiteralLoc;
7162 
7163     if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
7164       return;
7165 
7166     if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
7167         SanitizerMask())
7168       S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
7169     else if (isGlobalVar(D) && SanitizerName != "address")
7170       S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7171           << AL << ExpectedFunctionOrMethod;
7172     Sanitizers.push_back(SanitizerName);
7173   }
7174 
7175   D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
7176                                               Sanitizers.size()));
7177 }
7178 
7179 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
7180                                          const ParsedAttr &AL) {
7181   StringRef AttrName = AL.getAttrName()->getName();
7182   normalizeName(AttrName);
7183   StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
7184                                 .Case("no_address_safety_analysis", "address")
7185                                 .Case("no_sanitize_address", "address")
7186                                 .Case("no_sanitize_thread", "thread")
7187                                 .Case("no_sanitize_memory", "memory");
7188   if (isGlobalVar(D) && SanitizerName != "address")
7189     S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7190         << AL << ExpectedFunction;
7191 
7192   // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
7193   // NoSanitizeAttr object; but we need to calculate the correct spelling list
7194   // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
7195   // has the same spellings as the index for NoSanitizeAttr. We don't have a
7196   // general way to "translate" between the two, so this hack attempts to work
7197   // around the issue with hard-coded indicies. This is critical for calling
7198   // getSpelling() or prettyPrint() on the resulting semantic attribute object
7199   // without failing assertions.
7200   unsigned TranslatedSpellingIndex = 0;
7201   if (AL.isC2xAttribute() || AL.isCXX11Attribute())
7202     TranslatedSpellingIndex = 1;
7203 
7204   AttributeCommonInfo Info = AL;
7205   Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
7206   D->addAttr(::new (S.Context)
7207                  NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
7208 }
7209 
7210 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7211   if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
7212     D->addAttr(Internal);
7213 }
7214 
7215 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7216   if (S.LangOpts.OpenCLVersion != 200)
7217     S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
7218         << AL << "2.0" << 0;
7219   else
7220     S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
7221                                                                    << "2.0";
7222 }
7223 
7224 /// Handles semantic checking for features that are common to all attributes,
7225 /// such as checking whether a parameter was properly specified, or the correct
7226 /// number of arguments were passed, etc.
7227 static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
7228                                           const ParsedAttr &AL) {
7229   // Several attributes carry different semantics than the parsing requires, so
7230   // those are opted out of the common argument checks.
7231   //
7232   // We also bail on unknown and ignored attributes because those are handled
7233   // as part of the target-specific handling logic.
7234   if (AL.getKind() == ParsedAttr::UnknownAttribute)
7235     return false;
7236   // Check whether the attribute requires specific language extensions to be
7237   // enabled.
7238   if (!AL.diagnoseLangOpts(S))
7239     return true;
7240   // Check whether the attribute appertains to the given subject.
7241   if (!AL.diagnoseAppertainsTo(S, D))
7242     return true;
7243   if (AL.hasCustomParsing())
7244     return false;
7245 
7246   if (AL.getMinArgs() == AL.getMaxArgs()) {
7247     // If there are no optional arguments, then checking for the argument count
7248     // is trivial.
7249     if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
7250       return true;
7251   } else {
7252     // There are optional arguments, so checking is slightly more involved.
7253     if (AL.getMinArgs() &&
7254         !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs()))
7255       return true;
7256     else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
7257              !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs()))
7258       return true;
7259   }
7260 
7261   if (S.CheckAttrTarget(AL))
7262     return true;
7263 
7264   return false;
7265 }
7266 
7267 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7268   if (D->isInvalidDecl())
7269     return;
7270 
7271   // Check if there is only one access qualifier.
7272   if (D->hasAttr<OpenCLAccessAttr>()) {
7273     if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
7274         AL.getSemanticSpelling()) {
7275       S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
7276           << AL.getAttrName()->getName() << AL.getRange();
7277     } else {
7278       S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
7279           << D->getSourceRange();
7280       D->setInvalidDecl(true);
7281       return;
7282     }
7283   }
7284 
7285   // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
7286   // image object can be read and written.
7287   // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
7288   // object. Using the read_write (or __read_write) qualifier with the pipe
7289   // qualifier is a compilation error.
7290   if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
7291     const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
7292     if (AL.getAttrName()->getName().find("read_write") != StringRef::npos) {
7293       if ((!S.getLangOpts().OpenCLCPlusPlus &&
7294            S.getLangOpts().OpenCLVersion < 200) ||
7295           DeclTy->isPipeType()) {
7296         S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
7297             << AL << PDecl->getType() << DeclTy->isImageType();
7298         D->setInvalidDecl(true);
7299         return;
7300       }
7301     }
7302   }
7303 
7304   D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
7305 }
7306 
7307 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7308   // The 'sycl_kernel' attribute applies only to function templates.
7309   const auto *FD = cast<FunctionDecl>(D);
7310   const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
7311   assert(FT && "Function template is expected");
7312 
7313   // Function template must have at least two template parameters.
7314   const TemplateParameterList *TL = FT->getTemplateParameters();
7315   if (TL->size() < 2) {
7316     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
7317     return;
7318   }
7319 
7320   // Template parameters must be typenames.
7321   for (unsigned I = 0; I < 2; ++I) {
7322     const NamedDecl *TParam = TL->getParam(I);
7323     if (isa<NonTypeTemplateParmDecl>(TParam)) {
7324       S.Diag(FT->getLocation(),
7325              diag::warn_sycl_kernel_invalid_template_param_type);
7326       return;
7327     }
7328   }
7329 
7330   // Function must have at least one argument.
7331   if (getFunctionOrMethodNumParams(D) != 1) {
7332     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
7333     return;
7334   }
7335 
7336   // Function must return void.
7337   QualType RetTy = getFunctionOrMethodResultType(D);
7338   if (!RetTy->isVoidType()) {
7339     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
7340     return;
7341   }
7342 
7343   handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
7344 }
7345 
7346 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
7347   if (!cast<VarDecl>(D)->hasGlobalStorage()) {
7348     S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
7349         << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
7350     return;
7351   }
7352 
7353   if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
7354     handleSimpleAttributeWithExclusions<AlwaysDestroyAttr, NoDestroyAttr>(S, D, A);
7355   else
7356     handleSimpleAttributeWithExclusions<NoDestroyAttr, AlwaysDestroyAttr>(S, D, A);
7357 }
7358 
7359 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7360   assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
7361          "uninitialized is only valid on automatic duration variables");
7362   D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
7363 }
7364 
7365 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
7366                                         bool DiagnoseFailure) {
7367   QualType Ty = VD->getType();
7368   if (!Ty->isObjCRetainableType()) {
7369     if (DiagnoseFailure) {
7370       S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
7371           << 0;
7372     }
7373     return false;
7374   }
7375 
7376   Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
7377 
7378   // Sema::inferObjCARCLifetime must run after processing decl attributes
7379   // (because __block lowers to an attribute), so if the lifetime hasn't been
7380   // explicitly specified, infer it locally now.
7381   if (LifetimeQual == Qualifiers::OCL_None)
7382     LifetimeQual = Ty->getObjCARCImplicitLifetime();
7383 
7384   // The attributes only really makes sense for __strong variables; ignore any
7385   // attempts to annotate a parameter with any other lifetime qualifier.
7386   if (LifetimeQual != Qualifiers::OCL_Strong) {
7387     if (DiagnoseFailure) {
7388       S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
7389           << 1;
7390     }
7391     return false;
7392   }
7393 
7394   // Tampering with the type of a VarDecl here is a bit of a hack, but we need
7395   // to ensure that the variable is 'const' so that we can error on
7396   // modification, which can otherwise over-release.
7397   VD->setType(Ty.withConst());
7398   VD->setARCPseudoStrong(true);
7399   return true;
7400 }
7401 
7402 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
7403                                              const ParsedAttr &AL) {
7404   if (auto *VD = dyn_cast<VarDecl>(D)) {
7405     assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
7406     if (!VD->hasLocalStorage()) {
7407       S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
7408           << 0;
7409       return;
7410     }
7411 
7412     if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
7413       return;
7414 
7415     handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
7416     return;
7417   }
7418 
7419   // If D is a function-like declaration (method, block, or function), then we
7420   // make every parameter psuedo-strong.
7421   unsigned NumParams =
7422       hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
7423   for (unsigned I = 0; I != NumParams; ++I) {
7424     auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
7425     QualType Ty = PVD->getType();
7426 
7427     // If a user wrote a parameter with __strong explicitly, then assume they
7428     // want "real" strong semantics for that parameter. This works because if
7429     // the parameter was written with __strong, then the strong qualifier will
7430     // be non-local.
7431     if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
7432         Qualifiers::OCL_Strong)
7433       continue;
7434 
7435     tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
7436   }
7437   handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
7438 }
7439 
7440 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7441   // Check that the return type is a `typedef int kern_return_t` or a typedef
7442   // around it, because otherwise MIG convention checks make no sense.
7443   // BlockDecl doesn't store a return type, so it's annoying to check,
7444   // so let's skip it for now.
7445   if (!isa<BlockDecl>(D)) {
7446     QualType T = getFunctionOrMethodResultType(D);
7447     bool IsKernReturnT = false;
7448     while (const auto *TT = T->getAs<TypedefType>()) {
7449       IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
7450       T = TT->desugar();
7451     }
7452     if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
7453       S.Diag(D->getBeginLoc(),
7454              diag::warn_mig_server_routine_does_not_return_kern_return_t);
7455       return;
7456     }
7457   }
7458 
7459   handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
7460 }
7461 
7462 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7463   // Warn if the return type is not a pointer or reference type.
7464   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7465     QualType RetTy = FD->getReturnType();
7466     if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
7467       S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
7468           << AL.getRange() << RetTy;
7469       return;
7470     }
7471   }
7472 
7473   handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
7474 }
7475 
7476 static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7477   if (AL.isUsedAsTypeAttr())
7478     return;
7479   // Warn if the parameter is definitely not an output parameter.
7480   if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
7481     if (PVD->getType()->isIntegerType()) {
7482       S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
7483           << AL.getRange();
7484       return;
7485     }
7486   }
7487   StringRef Argument;
7488   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
7489     return;
7490   D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
7491 }
7492 
7493 template<typename Attr>
7494 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7495   StringRef Argument;
7496   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
7497     return;
7498   D->addAttr(Attr::Create(S.Context, Argument, AL));
7499 }
7500 
7501 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7502   // The guard attribute takes a single identifier argument.
7503 
7504   if (!AL.isArgIdent(0)) {
7505     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7506         << AL << AANT_ArgumentIdentifier;
7507     return;
7508   }
7509 
7510   CFGuardAttr::GuardArg Arg;
7511   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
7512   if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
7513     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
7514     return;
7515   }
7516 
7517   D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
7518 }
7519 
7520 
7521 template <typename AttrTy>
7522 static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) {
7523   auto Attrs = D->specific_attrs<AttrTy>();
7524   auto I = llvm::find_if(Attrs,
7525                          [Name](const AttrTy *A) {
7526                            return A->getTCBName() == Name;
7527                          });
7528   return I == Attrs.end() ? nullptr : *I;
7529 }
7530 
7531 template <typename AttrTy, typename ConflictingAttrTy>
7532 static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7533   StringRef Argument;
7534   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
7535     return;
7536 
7537   // A function cannot be have both regular and leaf membership in the same TCB.
7538   if (const ConflictingAttrTy *ConflictingAttr =
7539       findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) {
7540     // We could attach a note to the other attribute but in this case
7541     // there's no need given how the two are very close to each other.
7542     S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes)
7543       << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName()
7544       << Argument;
7545 
7546     // Error recovery: drop the non-leaf attribute so that to suppress
7547     // all future warnings caused by erroneous attributes. The leaf attribute
7548     // needs to be kept because it can only suppresses warnings, not cause them.
7549     D->dropAttr<EnforceTCBAttr>();
7550     return;
7551   }
7552 
7553   D->addAttr(AttrTy::Create(S.Context, Argument, AL));
7554 }
7555 
7556 template <typename AttrTy, typename ConflictingAttrTy>
7557 static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) {
7558   // Check if the new redeclaration has different leaf-ness in the same TCB.
7559   StringRef TCBName = AL.getTCBName();
7560   if (const ConflictingAttrTy *ConflictingAttr =
7561       findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) {
7562     S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes)
7563       << ConflictingAttr->getAttrName()->getName()
7564       << AL.getAttrName()->getName() << TCBName;
7565 
7566     // Add a note so that the user could easily find the conflicting attribute.
7567     S.Diag(AL.getLoc(), diag::note_conflicting_attribute);
7568 
7569     // More error recovery.
7570     D->dropAttr<EnforceTCBAttr>();
7571     return nullptr;
7572   }
7573 
7574   ASTContext &Context = S.getASTContext();
7575   return ::new(Context) AttrTy(Context, AL, AL.getTCBName());
7576 }
7577 
7578 EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) {
7579   return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>(
7580       *this, D, AL);
7581 }
7582 
7583 EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr(
7584     Decl *D, const EnforceTCBLeafAttr &AL) {
7585   return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>(
7586       *this, D, AL);
7587 }
7588 
7589 //===----------------------------------------------------------------------===//
7590 // Top Level Sema Entry Points
7591 //===----------------------------------------------------------------------===//
7592 
7593 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
7594 /// the attribute applies to decls.  If the attribute is a type attribute, just
7595 /// silently ignore it if a GNU attribute.
7596 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
7597                                  const ParsedAttr &AL,
7598                                  bool IncludeCXX11Attributes) {
7599   if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
7600     return;
7601 
7602   // Ignore C++11 attributes on declarator chunks: they appertain to the type
7603   // instead.
7604   if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
7605     return;
7606 
7607   // Unknown attributes are automatically warned on. Target-specific attributes
7608   // which do not apply to the current target architecture are treated as
7609   // though they were unknown attributes.
7610   if (AL.getKind() == ParsedAttr::UnknownAttribute ||
7611       !AL.existsInTarget(S.Context.getTargetInfo())) {
7612     S.Diag(AL.getLoc(),
7613            AL.isDeclspecAttribute()
7614                ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
7615                : (unsigned)diag::warn_unknown_attribute_ignored)
7616         << AL << AL.getRange();
7617     return;
7618   }
7619 
7620   if (handleCommonAttributeFeatures(S, D, AL))
7621     return;
7622 
7623   switch (AL.getKind()) {
7624   default:
7625     if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled)
7626       break;
7627     if (!AL.isStmtAttr()) {
7628       // Type attributes are handled elsewhere; silently move on.
7629       assert(AL.isTypeAttr() && "Non-type attribute not handled");
7630       break;
7631     }
7632     S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
7633         << AL << D->getLocation();
7634     break;
7635   case ParsedAttr::AT_Interrupt:
7636     handleInterruptAttr(S, D, AL);
7637     break;
7638   case ParsedAttr::AT_X86ForceAlignArgPointer:
7639     handleX86ForceAlignArgPointerAttr(S, D, AL);
7640     break;
7641   case ParsedAttr::AT_DLLExport:
7642   case ParsedAttr::AT_DLLImport:
7643     handleDLLAttr(S, D, AL);
7644     break;
7645   case ParsedAttr::AT_Mips16:
7646     handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
7647                                         MipsInterruptAttr>(S, D, AL);
7648     break;
7649   case ParsedAttr::AT_MicroMips:
7650     handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
7651     break;
7652   case ParsedAttr::AT_MipsLongCall:
7653     handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
7654         S, D, AL);
7655     break;
7656   case ParsedAttr::AT_MipsShortCall:
7657     handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
7658         S, D, AL);
7659     break;
7660   case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
7661     handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
7662     break;
7663   case ParsedAttr::AT_AMDGPUWavesPerEU:
7664     handleAMDGPUWavesPerEUAttr(S, D, AL);
7665     break;
7666   case ParsedAttr::AT_AMDGPUNumSGPR:
7667     handleAMDGPUNumSGPRAttr(S, D, AL);
7668     break;
7669   case ParsedAttr::AT_AMDGPUNumVGPR:
7670     handleAMDGPUNumVGPRAttr(S, D, AL);
7671     break;
7672   case ParsedAttr::AT_AVRSignal:
7673     handleAVRSignalAttr(S, D, AL);
7674     break;
7675   case ParsedAttr::AT_BPFPreserveAccessIndex:
7676     handleBPFPreserveAccessIndexAttr(S, D, AL);
7677     break;
7678   case ParsedAttr::AT_WebAssemblyExportName:
7679     handleWebAssemblyExportNameAttr(S, D, AL);
7680     break;
7681   case ParsedAttr::AT_WebAssemblyImportModule:
7682     handleWebAssemblyImportModuleAttr(S, D, AL);
7683     break;
7684   case ParsedAttr::AT_WebAssemblyImportName:
7685     handleWebAssemblyImportNameAttr(S, D, AL);
7686     break;
7687   case ParsedAttr::AT_IBOutlet:
7688     handleIBOutlet(S, D, AL);
7689     break;
7690   case ParsedAttr::AT_IBOutletCollection:
7691     handleIBOutletCollection(S, D, AL);
7692     break;
7693   case ParsedAttr::AT_IFunc:
7694     handleIFuncAttr(S, D, AL);
7695     break;
7696   case ParsedAttr::AT_Alias:
7697     handleAliasAttr(S, D, AL);
7698     break;
7699   case ParsedAttr::AT_Aligned:
7700     handleAlignedAttr(S, D, AL);
7701     break;
7702   case ParsedAttr::AT_AlignValue:
7703     handleAlignValueAttr(S, D, AL);
7704     break;
7705   case ParsedAttr::AT_AllocSize:
7706     handleAllocSizeAttr(S, D, AL);
7707     break;
7708   case ParsedAttr::AT_AlwaysInline:
7709     handleAlwaysInlineAttr(S, D, AL);
7710     break;
7711   case ParsedAttr::AT_AnalyzerNoReturn:
7712     handleAnalyzerNoReturnAttr(S, D, AL);
7713     break;
7714   case ParsedAttr::AT_TLSModel:
7715     handleTLSModelAttr(S, D, AL);
7716     break;
7717   case ParsedAttr::AT_Annotate:
7718     handleAnnotateAttr(S, D, AL);
7719     break;
7720   case ParsedAttr::AT_Availability:
7721     handleAvailabilityAttr(S, D, AL);
7722     break;
7723   case ParsedAttr::AT_CarriesDependency:
7724     handleDependencyAttr(S, scope, D, AL);
7725     break;
7726   case ParsedAttr::AT_CPUDispatch:
7727   case ParsedAttr::AT_CPUSpecific:
7728     handleCPUSpecificAttr(S, D, AL);
7729     break;
7730   case ParsedAttr::AT_Common:
7731     handleCommonAttr(S, D, AL);
7732     break;
7733   case ParsedAttr::AT_CUDAConstant:
7734     handleConstantAttr(S, D, AL);
7735     break;
7736   case ParsedAttr::AT_PassObjectSize:
7737     handlePassObjectSizeAttr(S, D, AL);
7738     break;
7739   case ParsedAttr::AT_Constructor:
7740       handleConstructorAttr(S, D, AL);
7741     break;
7742   case ParsedAttr::AT_Deprecated:
7743     handleDeprecatedAttr(S, D, AL);
7744     break;
7745   case ParsedAttr::AT_Destructor:
7746       handleDestructorAttr(S, D, AL);
7747     break;
7748   case ParsedAttr::AT_EnableIf:
7749     handleEnableIfAttr(S, D, AL);
7750     break;
7751   case ParsedAttr::AT_DiagnoseIf:
7752     handleDiagnoseIfAttr(S, D, AL);
7753     break;
7754   case ParsedAttr::AT_NoBuiltin:
7755     handleNoBuiltinAttr(S, D, AL);
7756     break;
7757   case ParsedAttr::AT_ExtVectorType:
7758     handleExtVectorTypeAttr(S, D, AL);
7759     break;
7760   case ParsedAttr::AT_ExternalSourceSymbol:
7761     handleExternalSourceSymbolAttr(S, D, AL);
7762     break;
7763   case ParsedAttr::AT_MinSize:
7764     handleMinSizeAttr(S, D, AL);
7765     break;
7766   case ParsedAttr::AT_OptimizeNone:
7767     handleOptimizeNoneAttr(S, D, AL);
7768     break;
7769   case ParsedAttr::AT_EnumExtensibility:
7770     handleEnumExtensibilityAttr(S, D, AL);
7771     break;
7772   case ParsedAttr::AT_SYCLKernel:
7773     handleSYCLKernelAttr(S, D, AL);
7774     break;
7775   case ParsedAttr::AT_Format:
7776     handleFormatAttr(S, D, AL);
7777     break;
7778   case ParsedAttr::AT_FormatArg:
7779     handleFormatArgAttr(S, D, AL);
7780     break;
7781   case ParsedAttr::AT_Callback:
7782     handleCallbackAttr(S, D, AL);
7783     break;
7784   case ParsedAttr::AT_CalledOnce:
7785     handleCalledOnceAttr(S, D, AL);
7786     break;
7787   case ParsedAttr::AT_CUDAGlobal:
7788     handleGlobalAttr(S, D, AL);
7789     break;
7790   case ParsedAttr::AT_CUDADevice:
7791     handleDeviceAttr(S, D, AL);
7792     break;
7793   case ParsedAttr::AT_CUDAHost:
7794     handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
7795     break;
7796   case ParsedAttr::AT_CUDADeviceBuiltinSurfaceType:
7797     handleSimpleAttributeWithExclusions<CUDADeviceBuiltinSurfaceTypeAttr,
7798                                         CUDADeviceBuiltinTextureTypeAttr>(S, D,
7799                                                                           AL);
7800     break;
7801   case ParsedAttr::AT_CUDADeviceBuiltinTextureType:
7802     handleSimpleAttributeWithExclusions<CUDADeviceBuiltinTextureTypeAttr,
7803                                         CUDADeviceBuiltinSurfaceTypeAttr>(S, D,
7804                                                                           AL);
7805     break;
7806   case ParsedAttr::AT_GNUInline:
7807     handleGNUInlineAttr(S, D, AL);
7808     break;
7809   case ParsedAttr::AT_CUDALaunchBounds:
7810     handleLaunchBoundsAttr(S, D, AL);
7811     break;
7812   case ParsedAttr::AT_Restrict:
7813     handleRestrictAttr(S, D, AL);
7814     break;
7815   case ParsedAttr::AT_Mode:
7816     handleModeAttr(S, D, AL);
7817     break;
7818   case ParsedAttr::AT_NonNull:
7819     if (auto *PVD = dyn_cast<ParmVarDecl>(D))
7820       handleNonNullAttrParameter(S, PVD, AL);
7821     else
7822       handleNonNullAttr(S, D, AL);
7823     break;
7824   case ParsedAttr::AT_ReturnsNonNull:
7825     handleReturnsNonNullAttr(S, D, AL);
7826     break;
7827   case ParsedAttr::AT_NoEscape:
7828     handleNoEscapeAttr(S, D, AL);
7829     break;
7830   case ParsedAttr::AT_AssumeAligned:
7831     handleAssumeAlignedAttr(S, D, AL);
7832     break;
7833   case ParsedAttr::AT_AllocAlign:
7834     handleAllocAlignAttr(S, D, AL);
7835     break;
7836   case ParsedAttr::AT_Ownership:
7837     handleOwnershipAttr(S, D, AL);
7838     break;
7839   case ParsedAttr::AT_Cold:
7840     handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
7841     break;
7842   case ParsedAttr::AT_Hot:
7843     handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
7844     break;
7845   case ParsedAttr::AT_Naked:
7846     handleNakedAttr(S, D, AL);
7847     break;
7848   case ParsedAttr::AT_NoReturn:
7849     handleNoReturnAttr(S, D, AL);
7850     break;
7851   case ParsedAttr::AT_AnyX86NoCfCheck:
7852     handleNoCfCheckAttr(S, D, AL);
7853     break;
7854   case ParsedAttr::AT_Leaf:
7855     handleSimpleAttribute<LeafAttr>(S, D, AL);
7856     break;
7857   case ParsedAttr::AT_NoThrow:
7858     if (!AL.isUsedAsTypeAttr())
7859       handleSimpleAttribute<NoThrowAttr>(S, D, AL);
7860     break;
7861   case ParsedAttr::AT_CUDAShared:
7862     handleSharedAttr(S, D, AL);
7863     break;
7864   case ParsedAttr::AT_VecReturn:
7865     handleVecReturnAttr(S, D, AL);
7866     break;
7867   case ParsedAttr::AT_ObjCOwnership:
7868     handleObjCOwnershipAttr(S, D, AL);
7869     break;
7870   case ParsedAttr::AT_ObjCPreciseLifetime:
7871     handleObjCPreciseLifetimeAttr(S, D, AL);
7872     break;
7873   case ParsedAttr::AT_ObjCReturnsInnerPointer:
7874     handleObjCReturnsInnerPointerAttr(S, D, AL);
7875     break;
7876   case ParsedAttr::AT_ObjCRequiresSuper:
7877     handleObjCRequiresSuperAttr(S, D, AL);
7878     break;
7879   case ParsedAttr::AT_ObjCBridge:
7880     handleObjCBridgeAttr(S, D, AL);
7881     break;
7882   case ParsedAttr::AT_ObjCBridgeMutable:
7883     handleObjCBridgeMutableAttr(S, D, AL);
7884     break;
7885   case ParsedAttr::AT_ObjCBridgeRelated:
7886     handleObjCBridgeRelatedAttr(S, D, AL);
7887     break;
7888   case ParsedAttr::AT_ObjCDesignatedInitializer:
7889     handleObjCDesignatedInitializer(S, D, AL);
7890     break;
7891   case ParsedAttr::AT_ObjCRuntimeName:
7892     handleObjCRuntimeName(S, D, AL);
7893     break;
7894   case ParsedAttr::AT_ObjCBoxable:
7895     handleObjCBoxable(S, D, AL);
7896     break;
7897   case ParsedAttr::AT_NSErrorDomain:
7898     handleNSErrorDomain(S, D, AL);
7899     break;
7900   case ParsedAttr::AT_CFAuditedTransfer:
7901     handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
7902                                         CFUnknownTransferAttr>(S, D, AL);
7903     break;
7904   case ParsedAttr::AT_CFUnknownTransfer:
7905     handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
7906                                         CFAuditedTransferAttr>(S, D, AL);
7907     break;
7908   case ParsedAttr::AT_CFConsumed:
7909   case ParsedAttr::AT_NSConsumed:
7910   case ParsedAttr::AT_OSConsumed:
7911     S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
7912                        /*IsTemplateInstantiation=*/false);
7913     break;
7914   case ParsedAttr::AT_OSReturnsRetainedOnZero:
7915     handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
7916         S, D, AL, isValidOSObjectOutParameter(D),
7917         diag::warn_ns_attribute_wrong_parameter_type,
7918         /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
7919     break;
7920   case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
7921     handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
7922         S, D, AL, isValidOSObjectOutParameter(D),
7923         diag::warn_ns_attribute_wrong_parameter_type,
7924         /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
7925     break;
7926   case ParsedAttr::AT_NSReturnsAutoreleased:
7927   case ParsedAttr::AT_NSReturnsNotRetained:
7928   case ParsedAttr::AT_NSReturnsRetained:
7929   case ParsedAttr::AT_CFReturnsNotRetained:
7930   case ParsedAttr::AT_CFReturnsRetained:
7931   case ParsedAttr::AT_OSReturnsNotRetained:
7932   case ParsedAttr::AT_OSReturnsRetained:
7933     handleXReturnsXRetainedAttr(S, D, AL);
7934     break;
7935   case ParsedAttr::AT_WorkGroupSizeHint:
7936     handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
7937     break;
7938   case ParsedAttr::AT_ReqdWorkGroupSize:
7939     handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
7940     break;
7941   case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
7942     handleSubGroupSize(S, D, AL);
7943     break;
7944   case ParsedAttr::AT_VecTypeHint:
7945     handleVecTypeHint(S, D, AL);
7946     break;
7947   case ParsedAttr::AT_InitPriority:
7948     if (S.Context.getTargetInfo().getTriple().isOSAIX())
7949       llvm::report_fatal_error(
7950           "'init_priority' attribute is not yet supported on AIX");
7951     else
7952       handleInitPriorityAttr(S, D, AL);
7953     break;
7954   case ParsedAttr::AT_Packed:
7955     handlePackedAttr(S, D, AL);
7956     break;
7957   case ParsedAttr::AT_PreferredName:
7958     handlePreferredName(S, D, AL);
7959     break;
7960   case ParsedAttr::AT_Section:
7961     handleSectionAttr(S, D, AL);
7962     break;
7963   case ParsedAttr::AT_SpeculativeLoadHardening:
7964     handleSimpleAttributeWithExclusions<SpeculativeLoadHardeningAttr,
7965                                         NoSpeculativeLoadHardeningAttr>(S, D,
7966                                                                         AL);
7967     break;
7968   case ParsedAttr::AT_NoSpeculativeLoadHardening:
7969     handleSimpleAttributeWithExclusions<NoSpeculativeLoadHardeningAttr,
7970                                         SpeculativeLoadHardeningAttr>(S, D, AL);
7971     break;
7972   case ParsedAttr::AT_CodeSeg:
7973     handleCodeSegAttr(S, D, AL);
7974     break;
7975   case ParsedAttr::AT_Target:
7976     handleTargetAttr(S, D, AL);
7977     break;
7978   case ParsedAttr::AT_MinVectorWidth:
7979     handleMinVectorWidthAttr(S, D, AL);
7980     break;
7981   case ParsedAttr::AT_Unavailable:
7982     handleAttrWithMessage<UnavailableAttr>(S, D, AL);
7983     break;
7984   case ParsedAttr::AT_Assumption:
7985     handleAssumumptionAttr(S, D, AL);
7986     break;
7987   case ParsedAttr::AT_ObjCDirect:
7988     handleObjCDirectAttr(S, D, AL);
7989     break;
7990   case ParsedAttr::AT_ObjCNonRuntimeProtocol:
7991     handleObjCNonRuntimeProtocolAttr(S, D, AL);
7992     break;
7993   case ParsedAttr::AT_ObjCDirectMembers:
7994     handleObjCDirectMembersAttr(S, D, AL);
7995     handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
7996     break;
7997   case ParsedAttr::AT_ObjCExplicitProtocolImpl:
7998     handleObjCSuppresProtocolAttr(S, D, AL);
7999     break;
8000   case ParsedAttr::AT_Unused:
8001     handleUnusedAttr(S, D, AL);
8002     break;
8003   case ParsedAttr::AT_NotTailCalled:
8004     handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
8005         S, D, AL);
8006     break;
8007   case ParsedAttr::AT_DisableTailCalls:
8008     handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
8009                                                                          AL);
8010     break;
8011   case ParsedAttr::AT_NoMerge:
8012     handleSimpleAttribute<NoMergeAttr>(S, D, AL);
8013     break;
8014   case ParsedAttr::AT_Visibility:
8015     handleVisibilityAttr(S, D, AL, false);
8016     break;
8017   case ParsedAttr::AT_TypeVisibility:
8018     handleVisibilityAttr(S, D, AL, true);
8019     break;
8020   case ParsedAttr::AT_WarnUnusedResult:
8021     handleWarnUnusedResult(S, D, AL);
8022     break;
8023   case ParsedAttr::AT_WeakRef:
8024     handleWeakRefAttr(S, D, AL);
8025     break;
8026   case ParsedAttr::AT_WeakImport:
8027     handleWeakImportAttr(S, D, AL);
8028     break;
8029   case ParsedAttr::AT_TransparentUnion:
8030     handleTransparentUnionAttr(S, D, AL);
8031     break;
8032   case ParsedAttr::AT_ObjCMethodFamily:
8033     handleObjCMethodFamilyAttr(S, D, AL);
8034     break;
8035   case ParsedAttr::AT_ObjCNSObject:
8036     handleObjCNSObject(S, D, AL);
8037     break;
8038   case ParsedAttr::AT_ObjCIndependentClass:
8039     handleObjCIndependentClass(S, D, AL);
8040     break;
8041   case ParsedAttr::AT_Blocks:
8042     handleBlocksAttr(S, D, AL);
8043     break;
8044   case ParsedAttr::AT_Sentinel:
8045     handleSentinelAttr(S, D, AL);
8046     break;
8047   case ParsedAttr::AT_Cleanup:
8048     handleCleanupAttr(S, D, AL);
8049     break;
8050   case ParsedAttr::AT_NoDebug:
8051     handleNoDebugAttr(S, D, AL);
8052     break;
8053   case ParsedAttr::AT_CmseNSEntry:
8054     handleCmseNSEntryAttr(S, D, AL);
8055     break;
8056   case ParsedAttr::AT_StdCall:
8057   case ParsedAttr::AT_CDecl:
8058   case ParsedAttr::AT_FastCall:
8059   case ParsedAttr::AT_ThisCall:
8060   case ParsedAttr::AT_Pascal:
8061   case ParsedAttr::AT_RegCall:
8062   case ParsedAttr::AT_SwiftCall:
8063   case ParsedAttr::AT_VectorCall:
8064   case ParsedAttr::AT_MSABI:
8065   case ParsedAttr::AT_SysVABI:
8066   case ParsedAttr::AT_Pcs:
8067   case ParsedAttr::AT_IntelOclBicc:
8068   case ParsedAttr::AT_PreserveMost:
8069   case ParsedAttr::AT_PreserveAll:
8070   case ParsedAttr::AT_AArch64VectorPcs:
8071     handleCallConvAttr(S, D, AL);
8072     break;
8073   case ParsedAttr::AT_Suppress:
8074     handleSuppressAttr(S, D, AL);
8075     break;
8076   case ParsedAttr::AT_Owner:
8077   case ParsedAttr::AT_Pointer:
8078     handleLifetimeCategoryAttr(S, D, AL);
8079     break;
8080   case ParsedAttr::AT_OpenCLAccess:
8081     handleOpenCLAccessAttr(S, D, AL);
8082     break;
8083   case ParsedAttr::AT_OpenCLNoSVM:
8084     handleOpenCLNoSVMAttr(S, D, AL);
8085     break;
8086   case ParsedAttr::AT_SwiftContext:
8087     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext);
8088     break;
8089   case ParsedAttr::AT_SwiftErrorResult:
8090     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult);
8091     break;
8092   case ParsedAttr::AT_SwiftIndirectResult:
8093     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult);
8094     break;
8095   case ParsedAttr::AT_InternalLinkage:
8096     handleInternalLinkageAttr(S, D, AL);
8097     break;
8098 
8099   // Microsoft attributes:
8100   case ParsedAttr::AT_LayoutVersion:
8101     handleLayoutVersion(S, D, AL);
8102     break;
8103   case ParsedAttr::AT_Uuid:
8104     handleUuidAttr(S, D, AL);
8105     break;
8106   case ParsedAttr::AT_MSInheritance:
8107     handleMSInheritanceAttr(S, D, AL);
8108     break;
8109   case ParsedAttr::AT_Thread:
8110     handleDeclspecThreadAttr(S, D, AL);
8111     break;
8112 
8113   case ParsedAttr::AT_AbiTag:
8114     handleAbiTagAttr(S, D, AL);
8115     break;
8116   case ParsedAttr::AT_CFGuard:
8117     handleCFGuardAttr(S, D, AL);
8118     break;
8119 
8120   // Thread safety attributes:
8121   case ParsedAttr::AT_AssertExclusiveLock:
8122     handleAssertExclusiveLockAttr(S, D, AL);
8123     break;
8124   case ParsedAttr::AT_AssertSharedLock:
8125     handleAssertSharedLockAttr(S, D, AL);
8126     break;
8127   case ParsedAttr::AT_PtGuardedVar:
8128     handlePtGuardedVarAttr(S, D, AL);
8129     break;
8130   case ParsedAttr::AT_NoSanitize:
8131     handleNoSanitizeAttr(S, D, AL);
8132     break;
8133   case ParsedAttr::AT_NoSanitizeSpecific:
8134     handleNoSanitizeSpecificAttr(S, D, AL);
8135     break;
8136   case ParsedAttr::AT_GuardedBy:
8137     handleGuardedByAttr(S, D, AL);
8138     break;
8139   case ParsedAttr::AT_PtGuardedBy:
8140     handlePtGuardedByAttr(S, D, AL);
8141     break;
8142   case ParsedAttr::AT_ExclusiveTrylockFunction:
8143     handleExclusiveTrylockFunctionAttr(S, D, AL);
8144     break;
8145   case ParsedAttr::AT_LockReturned:
8146     handleLockReturnedAttr(S, D, AL);
8147     break;
8148   case ParsedAttr::AT_LocksExcluded:
8149     handleLocksExcludedAttr(S, D, AL);
8150     break;
8151   case ParsedAttr::AT_SharedTrylockFunction:
8152     handleSharedTrylockFunctionAttr(S, D, AL);
8153     break;
8154   case ParsedAttr::AT_AcquiredBefore:
8155     handleAcquiredBeforeAttr(S, D, AL);
8156     break;
8157   case ParsedAttr::AT_AcquiredAfter:
8158     handleAcquiredAfterAttr(S, D, AL);
8159     break;
8160 
8161   // Capability analysis attributes.
8162   case ParsedAttr::AT_Capability:
8163   case ParsedAttr::AT_Lockable:
8164     handleCapabilityAttr(S, D, AL);
8165     break;
8166   case ParsedAttr::AT_RequiresCapability:
8167     handleRequiresCapabilityAttr(S, D, AL);
8168     break;
8169 
8170   case ParsedAttr::AT_AssertCapability:
8171     handleAssertCapabilityAttr(S, D, AL);
8172     break;
8173   case ParsedAttr::AT_AcquireCapability:
8174     handleAcquireCapabilityAttr(S, D, AL);
8175     break;
8176   case ParsedAttr::AT_ReleaseCapability:
8177     handleReleaseCapabilityAttr(S, D, AL);
8178     break;
8179   case ParsedAttr::AT_TryAcquireCapability:
8180     handleTryAcquireCapabilityAttr(S, D, AL);
8181     break;
8182 
8183   // Consumed analysis attributes.
8184   case ParsedAttr::AT_Consumable:
8185     handleConsumableAttr(S, D, AL);
8186     break;
8187   case ParsedAttr::AT_CallableWhen:
8188     handleCallableWhenAttr(S, D, AL);
8189     break;
8190   case ParsedAttr::AT_ParamTypestate:
8191     handleParamTypestateAttr(S, D, AL);
8192     break;
8193   case ParsedAttr::AT_ReturnTypestate:
8194     handleReturnTypestateAttr(S, D, AL);
8195     break;
8196   case ParsedAttr::AT_SetTypestate:
8197     handleSetTypestateAttr(S, D, AL);
8198     break;
8199   case ParsedAttr::AT_TestTypestate:
8200     handleTestTypestateAttr(S, D, AL);
8201     break;
8202 
8203   // Type safety attributes.
8204   case ParsedAttr::AT_ArgumentWithTypeTag:
8205     handleArgumentWithTypeTagAttr(S, D, AL);
8206     break;
8207   case ParsedAttr::AT_TypeTagForDatatype:
8208     handleTypeTagForDatatypeAttr(S, D, AL);
8209     break;
8210 
8211   // Swift attributes.
8212   case ParsedAttr::AT_SwiftAsyncName:
8213     handleSwiftAsyncName(S, D, AL);
8214     break;
8215   case ParsedAttr::AT_SwiftAttr:
8216     handleSwiftAttrAttr(S, D, AL);
8217     break;
8218   case ParsedAttr::AT_SwiftBridge:
8219     handleSwiftBridge(S, D, AL);
8220     break;
8221   case ParsedAttr::AT_SwiftBridgedTypedef:
8222     handleSimpleAttribute<SwiftBridgedTypedefAttr>(S, D, AL);
8223     break;
8224   case ParsedAttr::AT_SwiftError:
8225     handleSwiftError(S, D, AL);
8226     break;
8227   case ParsedAttr::AT_SwiftName:
8228     handleSwiftName(S, D, AL);
8229     break;
8230   case ParsedAttr::AT_SwiftNewType:
8231     handleSwiftNewType(S, D, AL);
8232     break;
8233   case ParsedAttr::AT_SwiftObjCMembers:
8234     handleSimpleAttribute<SwiftObjCMembersAttr>(S, D, AL);
8235     break;
8236   case ParsedAttr::AT_SwiftPrivate:
8237     handleSimpleAttribute<SwiftPrivateAttr>(S, D, AL);
8238     break;
8239   case ParsedAttr::AT_SwiftAsync:
8240     handleSwiftAsyncAttr(S, D, AL);
8241     break;
8242 
8243   // XRay attributes.
8244   case ParsedAttr::AT_XRayLogArgs:
8245     handleXRayLogArgsAttr(S, D, AL);
8246     break;
8247 
8248   case ParsedAttr::AT_PatchableFunctionEntry:
8249     handlePatchableFunctionEntryAttr(S, D, AL);
8250     break;
8251 
8252   case ParsedAttr::AT_AlwaysDestroy:
8253   case ParsedAttr::AT_NoDestroy:
8254     handleDestroyAttr(S, D, AL);
8255     break;
8256 
8257   case ParsedAttr::AT_Uninitialized:
8258     handleUninitializedAttr(S, D, AL);
8259     break;
8260 
8261   case ParsedAttr::AT_LoaderUninitialized:
8262     handleSimpleAttribute<LoaderUninitializedAttr>(S, D, AL);
8263     break;
8264 
8265   case ParsedAttr::AT_ObjCExternallyRetained:
8266     handleObjCExternallyRetainedAttr(S, D, AL);
8267     break;
8268 
8269   case ParsedAttr::AT_MIGServerRoutine:
8270     handleMIGServerRoutineAttr(S, D, AL);
8271     break;
8272 
8273   case ParsedAttr::AT_MSAllocator:
8274     handleMSAllocatorAttr(S, D, AL);
8275     break;
8276 
8277   case ParsedAttr::AT_ArmBuiltinAlias:
8278     handleArmBuiltinAliasAttr(S, D, AL);
8279     break;
8280 
8281   case ParsedAttr::AT_AcquireHandle:
8282     handleAcquireHandleAttr(S, D, AL);
8283     break;
8284 
8285   case ParsedAttr::AT_ReleaseHandle:
8286     handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
8287     break;
8288 
8289   case ParsedAttr::AT_UseHandle:
8290     handleHandleAttr<UseHandleAttr>(S, D, AL);
8291     break;
8292 
8293   case ParsedAttr::AT_EnforceTCB:
8294     handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL);
8295     break;
8296 
8297   case ParsedAttr::AT_EnforceTCBLeaf:
8298     handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL);
8299     break;
8300   }
8301 }
8302 
8303 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
8304 /// attribute list to the specified decl, ignoring any type attributes.
8305 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
8306                                     const ParsedAttributesView &AttrList,
8307                                     bool IncludeCXX11Attributes) {
8308   if (AttrList.empty())
8309     return;
8310 
8311   for (const ParsedAttr &AL : AttrList)
8312     ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
8313 
8314   // FIXME: We should be able to handle these cases in TableGen.
8315   // GCC accepts
8316   // static int a9 __attribute__((weakref));
8317   // but that looks really pointless. We reject it.
8318   if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
8319     Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
8320         << cast<NamedDecl>(D);
8321     D->dropAttr<WeakRefAttr>();
8322     return;
8323   }
8324 
8325   // FIXME: We should be able to handle this in TableGen as well. It would be
8326   // good to have a way to specify "these attributes must appear as a group",
8327   // for these. Additionally, it would be good to have a way to specify "these
8328   // attribute must never appear as a group" for attributes like cold and hot.
8329   if (!D->hasAttr<OpenCLKernelAttr>()) {
8330     // These attributes cannot be applied to a non-kernel function.
8331     if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
8332       // FIXME: This emits a different error message than
8333       // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
8334       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8335       D->setInvalidDecl();
8336     } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
8337       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8338       D->setInvalidDecl();
8339     } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
8340       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8341       D->setInvalidDecl();
8342     } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
8343       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8344       D->setInvalidDecl();
8345     } else if (!D->hasAttr<CUDAGlobalAttr>()) {
8346       if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
8347         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8348             << A << ExpectedKernelFunction;
8349         D->setInvalidDecl();
8350       } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
8351         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8352             << A << ExpectedKernelFunction;
8353         D->setInvalidDecl();
8354       } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
8355         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8356             << A << ExpectedKernelFunction;
8357         D->setInvalidDecl();
8358       } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
8359         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8360             << A << ExpectedKernelFunction;
8361         D->setInvalidDecl();
8362       }
8363     }
8364   }
8365 
8366   // Do this check after processing D's attributes because the attribute
8367   // objc_method_family can change whether the given method is in the init
8368   // family, and it can be applied after objc_designated_initializer. This is a
8369   // bit of a hack, but we need it to be compatible with versions of clang that
8370   // processed the attribute list in the wrong order.
8371   if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
8372       cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
8373     Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
8374     D->dropAttr<ObjCDesignatedInitializerAttr>();
8375   }
8376 }
8377 
8378 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
8379 // attribute.
8380 void Sema::ProcessDeclAttributeDelayed(Decl *D,
8381                                        const ParsedAttributesView &AttrList) {
8382   for (const ParsedAttr &AL : AttrList)
8383     if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
8384       handleTransparentUnionAttr(*this, D, AL);
8385       break;
8386     }
8387 
8388   // For BPFPreserveAccessIndexAttr, we want to populate the attributes
8389   // to fields and inner records as well.
8390   if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
8391     handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D));
8392 }
8393 
8394 // Annotation attributes are the only attributes allowed after an access
8395 // specifier.
8396 bool Sema::ProcessAccessDeclAttributeList(
8397     AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
8398   for (const ParsedAttr &AL : AttrList) {
8399     if (AL.getKind() == ParsedAttr::AT_Annotate) {
8400       ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
8401     } else {
8402       Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
8403       return true;
8404     }
8405   }
8406   return false;
8407 }
8408 
8409 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
8410 /// contains any decl attributes that we should warn about.
8411 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
8412   for (const ParsedAttr &AL : A) {
8413     // Only warn if the attribute is an unignored, non-type attribute.
8414     if (AL.isUsedAsTypeAttr() || AL.isInvalid())
8415       continue;
8416     if (AL.getKind() == ParsedAttr::IgnoredAttribute)
8417       continue;
8418 
8419     if (AL.getKind() == ParsedAttr::UnknownAttribute) {
8420       S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
8421           << AL << AL.getRange();
8422     } else {
8423       S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
8424                                                             << AL.getRange();
8425     }
8426   }
8427 }
8428 
8429 /// checkUnusedDeclAttributes - Given a declarator which is not being
8430 /// used to build a declaration, complain about any decl attributes
8431 /// which might be lying around on it.
8432 void Sema::checkUnusedDeclAttributes(Declarator &D) {
8433   ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
8434   ::checkUnusedDeclAttributes(*this, D.getAttributes());
8435   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
8436     ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
8437 }
8438 
8439 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
8440 /// \#pragma weak needs a non-definition decl and source may not have one.
8441 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8442                                       SourceLocation Loc) {
8443   assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
8444   NamedDecl *NewD = nullptr;
8445   if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
8446     FunctionDecl *NewFD;
8447     // FIXME: Missing call to CheckFunctionDeclaration().
8448     // FIXME: Mangling?
8449     // FIXME: Is the qualifier info correct?
8450     // FIXME: Is the DeclContext correct?
8451     NewFD = FunctionDecl::Create(
8452         FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
8453         DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
8454         false /*isInlineSpecified*/, FD->hasPrototype(),
8455         ConstexprSpecKind::Unspecified, FD->getTrailingRequiresClause());
8456     NewD = NewFD;
8457 
8458     if (FD->getQualifier())
8459       NewFD->setQualifierInfo(FD->getQualifierLoc());
8460 
8461     // Fake up parameter variables; they are declared as if this were
8462     // a typedef.
8463     QualType FDTy = FD->getType();
8464     if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
8465       SmallVector<ParmVarDecl*, 16> Params;
8466       for (const auto &AI : FT->param_types()) {
8467         ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
8468         Param->setScopeInfo(0, Params.size());
8469         Params.push_back(Param);
8470       }
8471       NewFD->setParams(Params);
8472     }
8473   } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
8474     NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
8475                            VD->getInnerLocStart(), VD->getLocation(), II,
8476                            VD->getType(), VD->getTypeSourceInfo(),
8477                            VD->getStorageClass());
8478     if (VD->getQualifier())
8479       cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
8480   }
8481   return NewD;
8482 }
8483 
8484 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
8485 /// applied to it, possibly with an alias.
8486 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
8487   if (W.getUsed()) return; // only do this once
8488   W.setUsed(true);
8489   if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
8490     IdentifierInfo *NDId = ND->getIdentifier();
8491     NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
8492     NewD->addAttr(
8493         AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
8494     NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
8495                                            AttributeCommonInfo::AS_Pragma));
8496     WeakTopLevelDecl.push_back(NewD);
8497     // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
8498     // to insert Decl at TU scope, sorry.
8499     DeclContext *SavedContext = CurContext;
8500     CurContext = Context.getTranslationUnitDecl();
8501     NewD->setDeclContext(CurContext);
8502     NewD->setLexicalDeclContext(CurContext);
8503     PushOnScopeChains(NewD, S);
8504     CurContext = SavedContext;
8505   } else { // just add weak to existing
8506     ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
8507                                          AttributeCommonInfo::AS_Pragma));
8508   }
8509 }
8510 
8511 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
8512   // It's valid to "forward-declare" #pragma weak, in which case we
8513   // have to do this.
8514   LoadExternalWeakUndeclaredIdentifiers();
8515   if (!WeakUndeclaredIdentifiers.empty()) {
8516     NamedDecl *ND = nullptr;
8517     if (auto *VD = dyn_cast<VarDecl>(D))
8518       if (VD->isExternC())
8519         ND = VD;
8520     if (auto *FD = dyn_cast<FunctionDecl>(D))
8521       if (FD->isExternC())
8522         ND = FD;
8523     if (ND) {
8524       if (IdentifierInfo *Id = ND->getIdentifier()) {
8525         auto I = WeakUndeclaredIdentifiers.find(Id);
8526         if (I != WeakUndeclaredIdentifiers.end()) {
8527           WeakInfo W = I->second;
8528           DeclApplyPragmaWeak(S, ND, W);
8529           WeakUndeclaredIdentifiers[Id] = W;
8530         }
8531       }
8532     }
8533   }
8534 }
8535 
8536 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
8537 /// it, apply them to D.  This is a bit tricky because PD can have attributes
8538 /// specified in many different places, and we need to find and apply them all.
8539 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
8540   // Apply decl attributes from the DeclSpec if present.
8541   if (!PD.getDeclSpec().getAttributes().empty())
8542     ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
8543 
8544   // Walk the declarator structure, applying decl attributes that were in a type
8545   // position to the decl itself.  This handles cases like:
8546   //   int *__attr__(x)** D;
8547   // when X is a decl attribute.
8548   for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
8549     ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
8550                              /*IncludeCXX11Attributes=*/false);
8551 
8552   // Finally, apply any attributes on the decl itself.
8553   ProcessDeclAttributeList(S, D, PD.getAttributes());
8554 
8555   // Apply additional attributes specified by '#pragma clang attribute'.
8556   AddPragmaAttributes(S, D);
8557 }
8558 
8559 /// Is the given declaration allowed to use a forbidden type?
8560 /// If so, it'll still be annotated with an attribute that makes it
8561 /// illegal to actually use.
8562 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
8563                                    const DelayedDiagnostic &diag,
8564                                    UnavailableAttr::ImplicitReason &reason) {
8565   // Private ivars are always okay.  Unfortunately, people don't
8566   // always properly make their ivars private, even in system headers.
8567   // Plus we need to make fields okay, too.
8568   if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
8569       !isa<FunctionDecl>(D))
8570     return false;
8571 
8572   // Silently accept unsupported uses of __weak in both user and system
8573   // declarations when it's been disabled, for ease of integration with
8574   // -fno-objc-arc files.  We do have to take some care against attempts
8575   // to define such things;  for now, we've only done that for ivars
8576   // and properties.
8577   if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
8578     if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
8579         diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
8580       reason = UnavailableAttr::IR_ForbiddenWeak;
8581       return true;
8582     }
8583   }
8584 
8585   // Allow all sorts of things in system headers.
8586   if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
8587     // Currently, all the failures dealt with this way are due to ARC
8588     // restrictions.
8589     reason = UnavailableAttr::IR_ARCForbiddenType;
8590     return true;
8591   }
8592 
8593   return false;
8594 }
8595 
8596 /// Handle a delayed forbidden-type diagnostic.
8597 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
8598                                        Decl *D) {
8599   auto Reason = UnavailableAttr::IR_None;
8600   if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
8601     assert(Reason && "didn't set reason?");
8602     D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
8603     return;
8604   }
8605   if (S.getLangOpts().ObjCAutoRefCount)
8606     if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
8607       // FIXME: we may want to suppress diagnostics for all
8608       // kind of forbidden type messages on unavailable functions.
8609       if (FD->hasAttr<UnavailableAttr>() &&
8610           DD.getForbiddenTypeDiagnostic() ==
8611               diag::err_arc_array_param_no_ownership) {
8612         DD.Triggered = true;
8613         return;
8614       }
8615     }
8616 
8617   S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
8618       << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
8619   DD.Triggered = true;
8620 }
8621 
8622 
8623 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
8624   assert(DelayedDiagnostics.getCurrentPool());
8625   DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
8626   DelayedDiagnostics.popWithoutEmitting(state);
8627 
8628   // When delaying diagnostics to run in the context of a parsed
8629   // declaration, we only want to actually emit anything if parsing
8630   // succeeds.
8631   if (!decl) return;
8632 
8633   // We emit all the active diagnostics in this pool or any of its
8634   // parents.  In general, we'll get one pool for the decl spec
8635   // and a child pool for each declarator; in a decl group like:
8636   //   deprecated_typedef foo, *bar, baz();
8637   // only the declarator pops will be passed decls.  This is correct;
8638   // we really do need to consider delayed diagnostics from the decl spec
8639   // for each of the different declarations.
8640   const DelayedDiagnosticPool *pool = &poppedPool;
8641   do {
8642     bool AnyAccessFailures = false;
8643     for (DelayedDiagnosticPool::pool_iterator
8644            i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
8645       // This const_cast is a bit lame.  Really, Triggered should be mutable.
8646       DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
8647       if (diag.Triggered)
8648         continue;
8649 
8650       switch (diag.Kind) {
8651       case DelayedDiagnostic::Availability:
8652         // Don't bother giving deprecation/unavailable diagnostics if
8653         // the decl is invalid.
8654         if (!decl->isInvalidDecl())
8655           handleDelayedAvailabilityCheck(diag, decl);
8656         break;
8657 
8658       case DelayedDiagnostic::Access:
8659         // Only produce one access control diagnostic for a structured binding
8660         // declaration: we don't need to tell the user that all the fields are
8661         // inaccessible one at a time.
8662         if (AnyAccessFailures && isa<DecompositionDecl>(decl))
8663           continue;
8664         HandleDelayedAccessCheck(diag, decl);
8665         if (diag.Triggered)
8666           AnyAccessFailures = true;
8667         break;
8668 
8669       case DelayedDiagnostic::ForbiddenType:
8670         handleDelayedForbiddenType(*this, diag, decl);
8671         break;
8672       }
8673     }
8674   } while ((pool = pool->getParent()));
8675 }
8676 
8677 /// Given a set of delayed diagnostics, re-emit them as if they had
8678 /// been delayed in the current context instead of in the given pool.
8679 /// Essentially, this just moves them to the current pool.
8680 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
8681   DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
8682   assert(curPool && "re-emitting in undelayed context not supported");
8683   curPool->steal(pool);
8684 }
8685