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