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