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