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