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