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() || Expr->isValueDependent() ||
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() || IdxExpr->isValueDependent() ||
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   int PriorityModifier = AL.isPragmaClangAttribute()
2500                              ? Sema::AP_PragmaClangAttribute
2501                              : Sema::AP_Explicit;
2502   AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2503       ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2504       Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2505       Sema::AMK_None, PriorityModifier);
2506   if (NewAttr)
2507     D->addAttr(NewAttr);
2508 
2509   // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2510   // matches before the start of the watchOS platform.
2511   if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2512     IdentifierInfo *NewII = nullptr;
2513     if (II->getName() == "ios")
2514       NewII = &S.Context.Idents.get("watchos");
2515     else if (II->getName() == "ios_app_extension")
2516       NewII = &S.Context.Idents.get("watchos_app_extension");
2517 
2518     if (NewII) {
2519         auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2520           if (Version.empty())
2521             return Version;
2522           auto Major = Version.getMajor();
2523           auto NewMajor = Major >= 9 ? Major - 7 : 0;
2524           if (NewMajor >= 2) {
2525             if (Version.getMinor().hasValue()) {
2526               if (Version.getSubminor().hasValue())
2527                 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2528                                     Version.getSubminor().getValue());
2529               else
2530                 return VersionTuple(NewMajor, Version.getMinor().getValue());
2531             }
2532             return VersionTuple(NewMajor);
2533           }
2534 
2535           return VersionTuple(2, 0);
2536         };
2537 
2538         auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2539         auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2540         auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2541 
2542         AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2543             ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2544             NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2545             Sema::AMK_None,
2546             PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2547         if (NewAttr)
2548           D->addAttr(NewAttr);
2549       }
2550   } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2551     // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2552     // matches before the start of the tvOS platform.
2553     IdentifierInfo *NewII = nullptr;
2554     if (II->getName() == "ios")
2555       NewII = &S.Context.Idents.get("tvos");
2556     else if (II->getName() == "ios_app_extension")
2557       NewII = &S.Context.Idents.get("tvos_app_extension");
2558 
2559     if (NewII) {
2560       AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2561           ND, AL, NewII, true /*Implicit*/, Introduced.Version,
2562           Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2563           Replacement, Sema::AMK_None,
2564           PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2565       if (NewAttr)
2566         D->addAttr(NewAttr);
2567       }
2568   } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2569                  llvm::Triple::IOS &&
2570              S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2571     auto GetSDKInfo = [&]() {
2572       return S.getDarwinSDKInfoForAvailabilityChecking(AL.getRange().getBegin(),
2573                                                        "macOS");
2574     };
2575 
2576     // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2577     IdentifierInfo *NewII = nullptr;
2578     if (II->getName() == "ios")
2579       NewII = &S.Context.Idents.get("maccatalyst");
2580     else if (II->getName() == "ios_app_extension")
2581       NewII = &S.Context.Idents.get("maccatalyst_app_extension");
2582     if (NewII) {
2583       auto MinMacCatalystVersion = [](const VersionTuple &V) {
2584         if (V.empty())
2585           return V;
2586         if (V.getMajor() < 13 ||
2587             (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
2588           return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2589         return V;
2590       };
2591       AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2592           ND, AL.getRange(), NewII, true /*Implicit*/,
2593           MinMacCatalystVersion(Introduced.Version),
2594           MinMacCatalystVersion(Deprecated.Version),
2595           MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2596           IsStrict, Replacement, Sema::AMK_None,
2597           PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2598       if (NewAttr)
2599         D->addAttr(NewAttr);
2600     } else if (II->getName() == "macos" && GetSDKInfo() &&
2601                (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
2602                 !Obsoleted.Version.empty())) {
2603       if (const auto *MacOStoMacCatalystMapping =
2604               GetSDKInfo()->getVersionMapping(
2605                   DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
2606         // Infer Mac Catalyst availability from the macOS availability attribute
2607         // if it has versioned availability. Don't infer 'unavailable'. This
2608         // inferred availability has lower priority than the other availability
2609         // attributes that are inferred from 'ios'.
2610         NewII = &S.Context.Idents.get("maccatalyst");
2611         auto RemapMacOSVersion =
2612             [&](const VersionTuple &V) -> Optional<VersionTuple> {
2613           if (V.empty())
2614             return None;
2615           // API_TO_BE_DEPRECATED is 100000.
2616           if (V.getMajor() == 100000)
2617             return VersionTuple(100000);
2618           // The minimum iosmac version is 13.1
2619           return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1), None);
2620         };
2621         Optional<VersionTuple> NewIntroduced =
2622                                    RemapMacOSVersion(Introduced.Version),
2623                                NewDeprecated =
2624                                    RemapMacOSVersion(Deprecated.Version),
2625                                NewObsoleted =
2626                                    RemapMacOSVersion(Obsoleted.Version);
2627         if (NewIntroduced || NewDeprecated || NewObsoleted) {
2628           auto VersionOrEmptyVersion =
2629               [](const Optional<VersionTuple> &V) -> VersionTuple {
2630             return V ? *V : VersionTuple();
2631           };
2632           AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2633               ND, AL.getRange(), NewII, true /*Implicit*/,
2634               VersionOrEmptyVersion(NewIntroduced),
2635               VersionOrEmptyVersion(NewDeprecated),
2636               VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2637               IsStrict, Replacement, Sema::AMK_None,
2638               PriorityModifier + Sema::AP_InferredFromOtherPlatform +
2639                   Sema::AP_InferredFromOtherPlatform);
2640           if (NewAttr)
2641             D->addAttr(NewAttr);
2642         }
2643       }
2644     }
2645   }
2646 }
2647 
2648 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2649                                            const ParsedAttr &AL) {
2650   if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3))
2651     return;
2652 
2653   StringRef Language;
2654   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2655     Language = SE->getString();
2656   StringRef DefinedIn;
2657   if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2658     DefinedIn = SE->getString();
2659   bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2660 
2661   D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2662       S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration));
2663 }
2664 
2665 template <class T>
2666 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2667                               typename T::VisibilityType value) {
2668   T *existingAttr = D->getAttr<T>();
2669   if (existingAttr) {
2670     typename T::VisibilityType existingValue = existingAttr->getVisibility();
2671     if (existingValue == value)
2672       return nullptr;
2673     S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2674     S.Diag(CI.getLoc(), diag::note_previous_attribute);
2675     D->dropAttr<T>();
2676   }
2677   return ::new (S.Context) T(S.Context, CI, value);
2678 }
2679 
2680 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2681                                           const AttributeCommonInfo &CI,
2682                                           VisibilityAttr::VisibilityType Vis) {
2683   return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2684 }
2685 
2686 TypeVisibilityAttr *
2687 Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2688                               TypeVisibilityAttr::VisibilityType Vis) {
2689   return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2690 }
2691 
2692 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2693                                  bool isTypeVisibility) {
2694   // Visibility attributes don't mean anything on a typedef.
2695   if (isa<TypedefNameDecl>(D)) {
2696     S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2697     return;
2698   }
2699 
2700   // 'type_visibility' can only go on a type or namespace.
2701   if (isTypeVisibility &&
2702       !(isa<TagDecl>(D) ||
2703         isa<ObjCInterfaceDecl>(D) ||
2704         isa<NamespaceDecl>(D))) {
2705     S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2706         << AL << ExpectedTypeOrNamespace;
2707     return;
2708   }
2709 
2710   // Check that the argument is a string literal.
2711   StringRef TypeStr;
2712   SourceLocation LiteralLoc;
2713   if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2714     return;
2715 
2716   VisibilityAttr::VisibilityType type;
2717   if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2718     S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2719                                                                 << TypeStr;
2720     return;
2721   }
2722 
2723   // Complain about attempts to use protected visibility on targets
2724   // (like Darwin) that don't support it.
2725   if (type == VisibilityAttr::Protected &&
2726       !S.Context.getTargetInfo().hasProtectedVisibility()) {
2727     S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2728     type = VisibilityAttr::Default;
2729   }
2730 
2731   Attr *newAttr;
2732   if (isTypeVisibility) {
2733     newAttr = S.mergeTypeVisibilityAttr(
2734         D, AL, (TypeVisibilityAttr::VisibilityType)type);
2735   } else {
2736     newAttr = S.mergeVisibilityAttr(D, AL, type);
2737   }
2738   if (newAttr)
2739     D->addAttr(newAttr);
2740 }
2741 
2742 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2743   // objc_direct cannot be set on methods declared in the context of a protocol
2744   if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
2745     S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2746     return;
2747   }
2748 
2749   if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2750     handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2751   } else {
2752     S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2753   }
2754 }
2755 
2756 static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
2757                                         const ParsedAttr &AL) {
2758   if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2759     handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2760   } else {
2761     S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2762   }
2763 }
2764 
2765 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2766   const auto *M = cast<ObjCMethodDecl>(D);
2767   if (!AL.isArgIdent(0)) {
2768     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2769         << AL << 1 << AANT_ArgumentIdentifier;
2770     return;
2771   }
2772 
2773   IdentifierLoc *IL = AL.getArgAsIdent(0);
2774   ObjCMethodFamilyAttr::FamilyKind F;
2775   if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2776     S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2777     return;
2778   }
2779 
2780   if (F == ObjCMethodFamilyAttr::OMF_init &&
2781       !M->getReturnType()->isObjCObjectPointerType()) {
2782     S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2783         << M->getReturnType();
2784     // Ignore the attribute.
2785     return;
2786   }
2787 
2788   D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
2789 }
2790 
2791 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2792   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2793     QualType T = TD->getUnderlyingType();
2794     if (!T->isCARCBridgableType()) {
2795       S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2796       return;
2797     }
2798   }
2799   else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2800     QualType T = PD->getType();
2801     if (!T->isCARCBridgableType()) {
2802       S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2803       return;
2804     }
2805   }
2806   else {
2807     // It is okay to include this attribute on properties, e.g.:
2808     //
2809     //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2810     //
2811     // In this case it follows tradition and suppresses an error in the above
2812     // case.
2813     S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2814   }
2815   D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
2816 }
2817 
2818 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2819   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2820     QualType T = TD->getUnderlyingType();
2821     if (!T->isObjCObjectPointerType()) {
2822       S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2823       return;
2824     }
2825   } else {
2826     S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2827     return;
2828   }
2829   D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
2830 }
2831 
2832 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2833   if (!AL.isArgIdent(0)) {
2834     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2835         << AL << 1 << AANT_ArgumentIdentifier;
2836     return;
2837   }
2838 
2839   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2840   BlocksAttr::BlockType type;
2841   if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2842     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2843     return;
2844   }
2845 
2846   D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
2847 }
2848 
2849 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2850   unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2851   if (AL.getNumArgs() > 0) {
2852     Expr *E = AL.getArgAsExpr(0);
2853     Optional<llvm::APSInt> Idx = llvm::APSInt(32);
2854     if (E->isTypeDependent() || E->isValueDependent() ||
2855         !(Idx = E->getIntegerConstantExpr(S.Context))) {
2856       S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2857           << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2858       return;
2859     }
2860 
2861     if (Idx->isSigned() && Idx->isNegative()) {
2862       S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2863         << E->getSourceRange();
2864       return;
2865     }
2866 
2867     sentinel = Idx->getZExtValue();
2868   }
2869 
2870   unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2871   if (AL.getNumArgs() > 1) {
2872     Expr *E = AL.getArgAsExpr(1);
2873     Optional<llvm::APSInt> Idx = llvm::APSInt(32);
2874     if (E->isTypeDependent() || E->isValueDependent() ||
2875         !(Idx = E->getIntegerConstantExpr(S.Context))) {
2876       S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2877           << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2878       return;
2879     }
2880     nullPos = Idx->getZExtValue();
2881 
2882     if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
2883       // FIXME: This error message could be improved, it would be nice
2884       // to say what the bounds actually are.
2885       S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2886         << E->getSourceRange();
2887       return;
2888     }
2889   }
2890 
2891   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2892     const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2893     if (isa<FunctionNoProtoType>(FT)) {
2894       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2895       return;
2896     }
2897 
2898     if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2899       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2900       return;
2901     }
2902   } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2903     if (!MD->isVariadic()) {
2904       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2905       return;
2906     }
2907   } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2908     if (!BD->isVariadic()) {
2909       S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2910       return;
2911     }
2912   } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2913     QualType Ty = V->getType();
2914     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2915       const FunctionType *FT = Ty->isFunctionPointerType()
2916                                    ? D->getFunctionType()
2917                                    : Ty->castAs<BlockPointerType>()
2918                                          ->getPointeeType()
2919                                          ->castAs<FunctionType>();
2920       if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2921         int m = Ty->isFunctionPointerType() ? 0 : 1;
2922         S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2923         return;
2924       }
2925     } else {
2926       S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2927           << AL << ExpectedFunctionMethodOrBlock;
2928       return;
2929     }
2930   } else {
2931     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2932         << AL << ExpectedFunctionMethodOrBlock;
2933     return;
2934   }
2935   D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
2936 }
2937 
2938 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2939   if (D->getFunctionType() &&
2940       D->getFunctionType()->getReturnType()->isVoidType() &&
2941       !isa<CXXConstructorDecl>(D)) {
2942     S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2943     return;
2944   }
2945   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2946     if (MD->getReturnType()->isVoidType()) {
2947       S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2948       return;
2949     }
2950 
2951   StringRef Str;
2952   if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
2953     // The standard attribute cannot be applied to variable declarations such
2954     // as a function pointer.
2955     if (isa<VarDecl>(D))
2956       S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
2957           << AL << "functions, classes, or enumerations";
2958 
2959     // If this is spelled as the standard C++17 attribute, but not in C++17,
2960     // warn about using it as an extension. If there are attribute arguments,
2961     // then claim it's a C++2a extension instead.
2962     // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2963     // extension warning for C2x mode.
2964     const LangOptions &LO = S.getLangOpts();
2965     if (AL.getNumArgs() == 1) {
2966       if (LO.CPlusPlus && !LO.CPlusPlus20)
2967         S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
2968 
2969       // Since this this is spelled [[nodiscard]], get the optional string
2970       // literal. If in C++ mode, but not in C++2a mode, diagnose as an
2971       // extension.
2972       // FIXME: C2x should support this feature as well, even as an extension.
2973       if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2974         return;
2975     } else if (LO.CPlusPlus && !LO.CPlusPlus17)
2976       S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2977   }
2978 
2979   D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
2980 }
2981 
2982 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2983   // weak_import only applies to variable & function declarations.
2984   bool isDef = false;
2985   if (!D->canBeWeakImported(isDef)) {
2986     if (isDef)
2987       S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2988         << "weak_import";
2989     else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2990              (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2991               (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2992       // Nothing to warn about here.
2993     } else
2994       S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2995           << AL << ExpectedVariableOrFunction;
2996 
2997     return;
2998   }
2999 
3000   D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
3001 }
3002 
3003 // Handles reqd_work_group_size and work_group_size_hint.
3004 template <typename WorkGroupAttr>
3005 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3006   uint32_t WGSize[3];
3007   for (unsigned i = 0; i < 3; ++i) {
3008     const Expr *E = AL.getArgAsExpr(i);
3009     if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
3010                              /*StrictlyUnsigned=*/true))
3011       return;
3012     if (WGSize[i] == 0) {
3013       S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3014           << AL << E->getSourceRange();
3015       return;
3016     }
3017   }
3018 
3019   WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3020   if (Existing && !(Existing->getXDim() == WGSize[0] &&
3021                     Existing->getYDim() == WGSize[1] &&
3022                     Existing->getZDim() == WGSize[2]))
3023     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3024 
3025   D->addAttr(::new (S.Context)
3026                  WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3027 }
3028 
3029 // Handles intel_reqd_sub_group_size.
3030 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3031   uint32_t SGSize;
3032   const Expr *E = AL.getArgAsExpr(0);
3033   if (!checkUInt32Argument(S, AL, E, SGSize))
3034     return;
3035   if (SGSize == 0) {
3036     S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3037         << AL << E->getSourceRange();
3038     return;
3039   }
3040 
3041   OpenCLIntelReqdSubGroupSizeAttr *Existing =
3042       D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
3043   if (Existing && Existing->getSubGroupSize() != SGSize)
3044     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3045 
3046   D->addAttr(::new (S.Context)
3047                  OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
3048 }
3049 
3050 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3051   if (!AL.hasParsedType()) {
3052     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3053     return;
3054   }
3055 
3056   TypeSourceInfo *ParmTSI = nullptr;
3057   QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
3058   assert(ParmTSI && "no type source info for attribute argument");
3059 
3060   if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
3061       (ParmType->isBooleanType() ||
3062        !ParmType->isIntegralType(S.getASTContext()))) {
3063     S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
3064     return;
3065   }
3066 
3067   if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
3068     if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
3069       S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3070       return;
3071     }
3072   }
3073 
3074   D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
3075 }
3076 
3077 SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3078                                     StringRef Name) {
3079   // Explicit or partial specializations do not inherit
3080   // the section attribute from the primary template.
3081   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3082     if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
3083         FD->isFunctionTemplateSpecialization())
3084       return nullptr;
3085   }
3086   if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3087     if (ExistingAttr->getName() == Name)
3088       return nullptr;
3089     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3090          << 1 /*section*/;
3091     Diag(CI.getLoc(), diag::note_previous_attribute);
3092     return nullptr;
3093   }
3094   return ::new (Context) SectionAttr(Context, CI, Name);
3095 }
3096 
3097 /// Used to implement to perform semantic checking on
3098 /// attribute((section("foo"))) specifiers.
3099 ///
3100 /// In this case, "foo" is passed in to be checked.  If the section
3101 /// specifier is invalid, return an Error that indicates the problem.
3102 ///
3103 /// This is a simple quality of implementation feature to catch errors
3104 /// and give good diagnostics in cases when the assembler or code generator
3105 /// would otherwise reject the section specifier.
3106 llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
3107   if (!Context.getTargetInfo().getTriple().isOSDarwin())
3108     return llvm::Error::success();
3109 
3110   // Let MCSectionMachO validate this.
3111   StringRef Segment, Section;
3112   unsigned TAA, StubSize;
3113   bool HasTAA;
3114   return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
3115                                                      TAA, HasTAA, StubSize);
3116 }
3117 
3118 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3119   if (llvm::Error E = isValidSectionSpecifier(SecName)) {
3120     Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3121         << toString(std::move(E)) << 1 /*'section'*/;
3122     return false;
3123   }
3124   return true;
3125 }
3126 
3127 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3128   // Make sure that there is a string literal as the sections's single
3129   // argument.
3130   StringRef Str;
3131   SourceLocation LiteralLoc;
3132   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3133     return;
3134 
3135   if (!S.checkSectionName(LiteralLoc, Str))
3136     return;
3137 
3138   SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
3139   if (NewAttr) {
3140     D->addAttr(NewAttr);
3141     if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl,
3142             ObjCPropertyDecl>(D))
3143       S.UnifySection(NewAttr->getName(),
3144                      ASTContext::PSF_Execute | ASTContext::PSF_Read,
3145                      cast<NamedDecl>(D));
3146   }
3147 }
3148 
3149 // This is used for `__declspec(code_seg("segname"))` on a decl.
3150 // `#pragma code_seg("segname")` uses checkSectionName() instead.
3151 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3152                              StringRef CodeSegName) {
3153   if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
3154     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3155         << toString(std::move(E)) << 0 /*'code-seg'*/;
3156     return false;
3157   }
3158 
3159   return true;
3160 }
3161 
3162 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3163                                     StringRef Name) {
3164   // Explicit or partial specializations do not inherit
3165   // the code_seg attribute from the primary template.
3166   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3167     if (FD->isFunctionTemplateSpecialization())
3168       return nullptr;
3169   }
3170   if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3171     if (ExistingAttr->getName() == Name)
3172       return nullptr;
3173     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3174          << 0 /*codeseg*/;
3175     Diag(CI.getLoc(), diag::note_previous_attribute);
3176     return nullptr;
3177   }
3178   return ::new (Context) CodeSegAttr(Context, CI, Name);
3179 }
3180 
3181 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3182   StringRef Str;
3183   SourceLocation LiteralLoc;
3184   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3185     return;
3186   if (!checkCodeSegName(S, LiteralLoc, Str))
3187     return;
3188   if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3189     if (!ExistingAttr->isImplicit()) {
3190       S.Diag(AL.getLoc(),
3191              ExistingAttr->getName() == Str
3192              ? diag::warn_duplicate_codeseg_attribute
3193              : diag::err_conflicting_codeseg_attribute);
3194       return;
3195     }
3196     D->dropAttr<CodeSegAttr>();
3197   }
3198   if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3199     D->addAttr(CSA);
3200 }
3201 
3202 // Check for things we'd like to warn about. Multiversioning issues are
3203 // handled later in the process, once we know how many exist.
3204 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3205   enum FirstParam { Unsupported, Duplicate, Unknown };
3206   enum SecondParam { None, Architecture, Tune };
3207   if (AttrStr.find("fpmath=") != StringRef::npos)
3208     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3209            << Unsupported << None << "fpmath=";
3210 
3211   // Diagnose use of tune if target doesn't support it.
3212   if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
3213       AttrStr.find("tune=") != StringRef::npos)
3214     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3215            << Unsupported << None << "tune=";
3216 
3217   ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3218 
3219   if (!ParsedAttrs.Architecture.empty() &&
3220       !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3221     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3222            << Unknown << Architecture << ParsedAttrs.Architecture;
3223 
3224   if (!ParsedAttrs.Tune.empty() &&
3225       !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
3226     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3227            << Unknown << Tune << ParsedAttrs.Tune;
3228 
3229   if (ParsedAttrs.DuplicateArchitecture)
3230     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3231            << Duplicate << None << "arch=";
3232   if (ParsedAttrs.DuplicateTune)
3233     return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3234            << Duplicate << None << "tune=";
3235 
3236   for (const auto &Feature : ParsedAttrs.Features) {
3237     auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3238     if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3239       return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3240              << Unsupported << None << CurFeature;
3241   }
3242 
3243   TargetInfo::BranchProtectionInfo BPI;
3244   StringRef Error;
3245   if (!ParsedAttrs.BranchProtection.empty() &&
3246       !Context.getTargetInfo().validateBranchProtection(
3247           ParsedAttrs.BranchProtection, BPI, Error)) {
3248     if (Error.empty())
3249       return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3250              << Unsupported << None << "branch-protection";
3251     else
3252       return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3253              << Error;
3254   }
3255 
3256   return false;
3257 }
3258 
3259 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3260   StringRef Str;
3261   SourceLocation LiteralLoc;
3262   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3263       S.checkTargetAttr(LiteralLoc, Str))
3264     return;
3265 
3266   TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3267   D->addAttr(NewAttr);
3268 }
3269 
3270 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3271   Expr *E = AL.getArgAsExpr(0);
3272   uint32_t VecWidth;
3273   if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3274     AL.setInvalid();
3275     return;
3276   }
3277 
3278   MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3279   if (Existing && Existing->getVectorWidth() != VecWidth) {
3280     S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3281     return;
3282   }
3283 
3284   D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3285 }
3286 
3287 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3288   Expr *E = AL.getArgAsExpr(0);
3289   SourceLocation Loc = E->getExprLoc();
3290   FunctionDecl *FD = nullptr;
3291   DeclarationNameInfo NI;
3292 
3293   // gcc only allows for simple identifiers. Since we support more than gcc, we
3294   // will warn the user.
3295   if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3296     if (DRE->hasQualifier())
3297       S.Diag(Loc, diag::warn_cleanup_ext);
3298     FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3299     NI = DRE->getNameInfo();
3300     if (!FD) {
3301       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3302         << NI.getName();
3303       return;
3304     }
3305   } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3306     if (ULE->hasExplicitTemplateArgs())
3307       S.Diag(Loc, diag::warn_cleanup_ext);
3308     FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3309     NI = ULE->getNameInfo();
3310     if (!FD) {
3311       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3312         << NI.getName();
3313       if (ULE->getType() == S.Context.OverloadTy)
3314         S.NoteAllOverloadCandidates(ULE);
3315       return;
3316     }
3317   } else {
3318     S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3319     return;
3320   }
3321 
3322   if (FD->getNumParams() != 1) {
3323     S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3324       << NI.getName();
3325     return;
3326   }
3327 
3328   // We're currently more strict than GCC about what function types we accept.
3329   // If this ever proves to be a problem it should be easy to fix.
3330   QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3331   QualType ParamTy = FD->getParamDecl(0)->getType();
3332   if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3333                                    ParamTy, Ty) != Sema::Compatible) {
3334     S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3335       << NI.getName() << ParamTy << Ty;
3336     return;
3337   }
3338 
3339   D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3340 }
3341 
3342 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3343                                         const ParsedAttr &AL) {
3344   if (!AL.isArgIdent(0)) {
3345     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3346         << AL << 0 << AANT_ArgumentIdentifier;
3347     return;
3348   }
3349 
3350   EnumExtensibilityAttr::Kind ExtensibilityKind;
3351   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3352   if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3353                                                ExtensibilityKind)) {
3354     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3355     return;
3356   }
3357 
3358   D->addAttr(::new (S.Context)
3359                  EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3360 }
3361 
3362 /// Handle __attribute__((format_arg((idx)))) attribute based on
3363 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3364 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3365   Expr *IdxExpr = AL.getArgAsExpr(0);
3366   ParamIdx Idx;
3367   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3368     return;
3369 
3370   // Make sure the format string is really a string.
3371   QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3372 
3373   bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3374   if (NotNSStringTy &&
3375       !isCFStringType(Ty, S.Context) &&
3376       (!Ty->isPointerType() ||
3377        !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3378     S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3379         << "a string type" << IdxExpr->getSourceRange()
3380         << getFunctionOrMethodParamRange(D, 0);
3381     return;
3382   }
3383   Ty = getFunctionOrMethodResultType(D);
3384   if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) &&
3385       !isCFStringType(Ty, S.Context) &&
3386       (!Ty->isPointerType() ||
3387        !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3388     S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3389         << (NotNSStringTy ? "string type" : "NSString")
3390         << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3391     return;
3392   }
3393 
3394   D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3395 }
3396 
3397 enum FormatAttrKind {
3398   CFStringFormat,
3399   NSStringFormat,
3400   StrftimeFormat,
3401   SupportedFormat,
3402   IgnoredFormat,
3403   InvalidFormat
3404 };
3405 
3406 /// getFormatAttrKind - Map from format attribute names to supported format
3407 /// types.
3408 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3409   return llvm::StringSwitch<FormatAttrKind>(Format)
3410       // Check for formats that get handled specially.
3411       .Case("NSString", NSStringFormat)
3412       .Case("CFString", CFStringFormat)
3413       .Case("strftime", StrftimeFormat)
3414 
3415       // Otherwise, check for supported formats.
3416       .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3417       .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3418       .Case("kprintf", SupportedFormat)         // OpenBSD.
3419       .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3420       .Case("os_trace", SupportedFormat)
3421       .Case("os_log", SupportedFormat)
3422 
3423       .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3424       .Default(InvalidFormat);
3425 }
3426 
3427 /// Handle __attribute__((init_priority(priority))) attributes based on
3428 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3429 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3430   if (!S.getLangOpts().CPlusPlus) {
3431     S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3432     return;
3433   }
3434 
3435   if (S.getCurFunctionOrMethodDecl()) {
3436     S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3437     AL.setInvalid();
3438     return;
3439   }
3440   QualType T = cast<VarDecl>(D)->getType();
3441   if (S.Context.getAsArrayType(T))
3442     T = S.Context.getBaseElementType(T);
3443   if (!T->getAs<RecordType>()) {
3444     S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3445     AL.setInvalid();
3446     return;
3447   }
3448 
3449   Expr *E = AL.getArgAsExpr(0);
3450   uint32_t prioritynum;
3451   if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3452     AL.setInvalid();
3453     return;
3454   }
3455 
3456   // Only perform the priority check if the attribute is outside of a system
3457   // header. Values <= 100 are reserved for the implementation, and libc++
3458   // benefits from being able to specify values in that range.
3459   if ((prioritynum < 101 || prioritynum > 65535) &&
3460       !S.getSourceManager().isInSystemHeader(AL.getLoc())) {
3461     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3462         << E->getSourceRange() << AL << 101 << 65535;
3463     AL.setInvalid();
3464     return;
3465   }
3466   D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3467 }
3468 
3469 ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3470                                 StringRef NewUserDiagnostic) {
3471   if (const auto *EA = D->getAttr<ErrorAttr>()) {
3472     std::string NewAttr = CI.getNormalizedFullName();
3473     assert((NewAttr == "error" || NewAttr == "warning") &&
3474            "unexpected normalized full name");
3475     bool Match = (EA->isError() && NewAttr == "error") ||
3476                  (EA->isWarning() && NewAttr == "warning");
3477     if (!Match) {
3478       Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
3479           << CI << EA;
3480       Diag(CI.getLoc(), diag::note_conflicting_attribute);
3481       return nullptr;
3482     }
3483     if (EA->getUserDiagnostic() != NewUserDiagnostic) {
3484       Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
3485       Diag(EA->getLoc(), diag::note_previous_attribute);
3486     }
3487     D->dropAttr<ErrorAttr>();
3488   }
3489   return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
3490 }
3491 
3492 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3493                                   IdentifierInfo *Format, int FormatIdx,
3494                                   int FirstArg) {
3495   // Check whether we already have an equivalent format attribute.
3496   for (auto *F : D->specific_attrs<FormatAttr>()) {
3497     if (F->getType() == Format &&
3498         F->getFormatIdx() == FormatIdx &&
3499         F->getFirstArg() == FirstArg) {
3500       // If we don't have a valid location for this attribute, adopt the
3501       // location.
3502       if (F->getLocation().isInvalid())
3503         F->setRange(CI.getRange());
3504       return nullptr;
3505     }
3506   }
3507 
3508   return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3509 }
3510 
3511 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3512 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3513 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3514   if (!AL.isArgIdent(0)) {
3515     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3516         << AL << 1 << AANT_ArgumentIdentifier;
3517     return;
3518   }
3519 
3520   // In C++ the implicit 'this' function parameter also counts, and they are
3521   // counted from one.
3522   bool HasImplicitThisParam = isInstanceMethod(D);
3523   unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3524 
3525   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3526   StringRef Format = II->getName();
3527 
3528   if (normalizeName(Format)) {
3529     // If we've modified the string name, we need a new identifier for it.
3530     II = &S.Context.Idents.get(Format);
3531   }
3532 
3533   // Check for supported formats.
3534   FormatAttrKind Kind = getFormatAttrKind(Format);
3535 
3536   if (Kind == IgnoredFormat)
3537     return;
3538 
3539   if (Kind == InvalidFormat) {
3540     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3541         << AL << II->getName();
3542     return;
3543   }
3544 
3545   // checks for the 2nd argument
3546   Expr *IdxExpr = AL.getArgAsExpr(1);
3547   uint32_t Idx;
3548   if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3549     return;
3550 
3551   if (Idx < 1 || Idx > NumArgs) {
3552     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3553         << AL << 2 << IdxExpr->getSourceRange();
3554     return;
3555   }
3556 
3557   // FIXME: Do we need to bounds check?
3558   unsigned ArgIdx = Idx - 1;
3559 
3560   if (HasImplicitThisParam) {
3561     if (ArgIdx == 0) {
3562       S.Diag(AL.getLoc(),
3563              diag::err_format_attribute_implicit_this_format_string)
3564         << IdxExpr->getSourceRange();
3565       return;
3566     }
3567     ArgIdx--;
3568   }
3569 
3570   // make sure the format string is really a string
3571   QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3572 
3573   if (Kind == CFStringFormat) {
3574     if (!isCFStringType(Ty, S.Context)) {
3575       S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3576         << "a CFString" << IdxExpr->getSourceRange()
3577         << getFunctionOrMethodParamRange(D, ArgIdx);
3578       return;
3579     }
3580   } else if (Kind == NSStringFormat) {
3581     // FIXME: do we need to check if the type is NSString*?  What are the
3582     // semantics?
3583     if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) {
3584       S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3585         << "an NSString" << IdxExpr->getSourceRange()
3586         << getFunctionOrMethodParamRange(D, ArgIdx);
3587       return;
3588     }
3589   } else if (!Ty->isPointerType() ||
3590              !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) {
3591     S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3592       << "a string type" << IdxExpr->getSourceRange()
3593       << getFunctionOrMethodParamRange(D, ArgIdx);
3594     return;
3595   }
3596 
3597   // check the 3rd argument
3598   Expr *FirstArgExpr = AL.getArgAsExpr(2);
3599   uint32_t FirstArg;
3600   if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3601     return;
3602 
3603   // check if the function is variadic if the 3rd argument non-zero
3604   if (FirstArg != 0) {
3605     if (isFunctionOrMethodVariadic(D)) {
3606       ++NumArgs; // +1 for ...
3607     } else {
3608       S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3609       return;
3610     }
3611   }
3612 
3613   // strftime requires FirstArg to be 0 because it doesn't read from any
3614   // variable the input is just the current time + the format string.
3615   if (Kind == StrftimeFormat) {
3616     if (FirstArg != 0) {
3617       S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3618         << FirstArgExpr->getSourceRange();
3619       return;
3620     }
3621   // if 0 it disables parameter checking (to use with e.g. va_list)
3622   } else if (FirstArg != 0 && FirstArg != NumArgs) {
3623     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3624         << AL << 3 << FirstArgExpr->getSourceRange();
3625     return;
3626   }
3627 
3628   FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3629   if (NewAttr)
3630     D->addAttr(NewAttr);
3631 }
3632 
3633 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3634 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3635   // The index that identifies the callback callee is mandatory.
3636   if (AL.getNumArgs() == 0) {
3637     S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3638         << AL.getRange();
3639     return;
3640   }
3641 
3642   bool HasImplicitThisParam = isInstanceMethod(D);
3643   int32_t NumArgs = getFunctionOrMethodNumParams(D);
3644 
3645   FunctionDecl *FD = D->getAsFunction();
3646   assert(FD && "Expected a function declaration!");
3647 
3648   llvm::StringMap<int> NameIdxMapping;
3649   NameIdxMapping["__"] = -1;
3650 
3651   NameIdxMapping["this"] = 0;
3652 
3653   int Idx = 1;
3654   for (const ParmVarDecl *PVD : FD->parameters())
3655     NameIdxMapping[PVD->getName()] = Idx++;
3656 
3657   auto UnknownName = NameIdxMapping.end();
3658 
3659   SmallVector<int, 8> EncodingIndices;
3660   for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3661     SourceRange SR;
3662     int32_t ArgIdx;
3663 
3664     if (AL.isArgIdent(I)) {
3665       IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3666       auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3667       if (It == UnknownName) {
3668         S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3669             << IdLoc->Ident << IdLoc->Loc;
3670         return;
3671       }
3672 
3673       SR = SourceRange(IdLoc->Loc);
3674       ArgIdx = It->second;
3675     } else if (AL.isArgExpr(I)) {
3676       Expr *IdxExpr = AL.getArgAsExpr(I);
3677 
3678       // If the expression is not parseable as an int32_t we have a problem.
3679       if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3680                                false)) {
3681         S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3682             << AL << (I + 1) << IdxExpr->getSourceRange();
3683         return;
3684       }
3685 
3686       // Check oob, excluding the special values, 0 and -1.
3687       if (ArgIdx < -1 || ArgIdx > NumArgs) {
3688         S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3689             << AL << (I + 1) << IdxExpr->getSourceRange();
3690         return;
3691       }
3692 
3693       SR = IdxExpr->getSourceRange();
3694     } else {
3695       llvm_unreachable("Unexpected ParsedAttr argument type!");
3696     }
3697 
3698     if (ArgIdx == 0 && !HasImplicitThisParam) {
3699       S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3700           << (I + 1) << SR;
3701       return;
3702     }
3703 
3704     // Adjust for the case we do not have an implicit "this" parameter. In this
3705     // case we decrease all positive values by 1 to get LLVM argument indices.
3706     if (!HasImplicitThisParam && ArgIdx > 0)
3707       ArgIdx -= 1;
3708 
3709     EncodingIndices.push_back(ArgIdx);
3710   }
3711 
3712   int CalleeIdx = EncodingIndices.front();
3713   // Check if the callee index is proper, thus not "this" and not "unknown".
3714   // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3715   // is false and positive if "HasImplicitThisParam" is true.
3716   if (CalleeIdx < (int)HasImplicitThisParam) {
3717     S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3718         << AL.getRange();
3719     return;
3720   }
3721 
3722   // Get the callee type, note the index adjustment as the AST doesn't contain
3723   // the this type (which the callee cannot reference anyway!).
3724   const Type *CalleeType =
3725       getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3726           .getTypePtr();
3727   if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3728     S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3729         << AL.getRange();
3730     return;
3731   }
3732 
3733   const Type *CalleeFnType =
3734       CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
3735 
3736   // TODO: Check the type of the callee arguments.
3737 
3738   const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3739   if (!CalleeFnProtoType) {
3740     S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3741         << AL.getRange();
3742     return;
3743   }
3744 
3745   if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3746     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3747         << AL << (unsigned)(EncodingIndices.size() - 1);
3748     return;
3749   }
3750 
3751   if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3752     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3753         << AL << (unsigned)(EncodingIndices.size() - 1);
3754     return;
3755   }
3756 
3757   if (CalleeFnProtoType->isVariadic()) {
3758     S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3759     return;
3760   }
3761 
3762   // Do not allow multiple callback attributes.
3763   if (D->hasAttr<CallbackAttr>()) {
3764     S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3765     return;
3766   }
3767 
3768   D->addAttr(::new (S.Context) CallbackAttr(
3769       S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3770 }
3771 
3772 static bool isFunctionLike(const Type &T) {
3773   // Check for explicit function types.
3774   // 'called_once' is only supported in Objective-C and it has
3775   // function pointers and block pointers.
3776   return T.isFunctionPointerType() || T.isBlockPointerType();
3777 }
3778 
3779 /// Handle 'called_once' attribute.
3780 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3781   // 'called_once' only applies to parameters representing functions.
3782   QualType T = cast<ParmVarDecl>(D)->getType();
3783 
3784   if (!isFunctionLike(*T)) {
3785     S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
3786     return;
3787   }
3788 
3789   D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
3790 }
3791 
3792 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3793   // Try to find the underlying union declaration.
3794   RecordDecl *RD = nullptr;
3795   const auto *TD = dyn_cast<TypedefNameDecl>(D);
3796   if (TD && TD->getUnderlyingType()->isUnionType())
3797     RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3798   else
3799     RD = dyn_cast<RecordDecl>(D);
3800 
3801   if (!RD || !RD->isUnion()) {
3802     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3803                                                               << ExpectedUnion;
3804     return;
3805   }
3806 
3807   if (!RD->isCompleteDefinition()) {
3808     if (!RD->isBeingDefined())
3809       S.Diag(AL.getLoc(),
3810              diag::warn_transparent_union_attribute_not_definition);
3811     return;
3812   }
3813 
3814   RecordDecl::field_iterator Field = RD->field_begin(),
3815                           FieldEnd = RD->field_end();
3816   if (Field == FieldEnd) {
3817     S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3818     return;
3819   }
3820 
3821   FieldDecl *FirstField = *Field;
3822   QualType FirstType = FirstField->getType();
3823   if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3824     S.Diag(FirstField->getLocation(),
3825            diag::warn_transparent_union_attribute_floating)
3826       << FirstType->isVectorType() << FirstType;
3827     return;
3828   }
3829 
3830   if (FirstType->isIncompleteType())
3831     return;
3832   uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3833   uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3834   for (; Field != FieldEnd; ++Field) {
3835     QualType FieldType = Field->getType();
3836     if (FieldType->isIncompleteType())
3837       return;
3838     // FIXME: this isn't fully correct; we also need to test whether the
3839     // members of the union would all have the same calling convention as the
3840     // first member of the union. Checking just the size and alignment isn't
3841     // sufficient (consider structs passed on the stack instead of in registers
3842     // as an example).
3843     if (S.Context.getTypeSize(FieldType) != FirstSize ||
3844         S.Context.getTypeAlign(FieldType) > FirstAlign) {
3845       // Warn if we drop the attribute.
3846       bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3847       unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
3848                                   : S.Context.getTypeAlign(FieldType);
3849       S.Diag(Field->getLocation(),
3850              diag::warn_transparent_union_attribute_field_size_align)
3851           << isSize << *Field << FieldBits;
3852       unsigned FirstBits = isSize ? FirstSize : FirstAlign;
3853       S.Diag(FirstField->getLocation(),
3854              diag::note_transparent_union_first_field_size_align)
3855           << isSize << FirstBits;
3856       return;
3857     }
3858   }
3859 
3860   RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3861 }
3862 
3863 void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
3864                              StringRef Str, MutableArrayRef<Expr *> Args) {
3865   auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
3866   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
3867   for (unsigned Idx = 0; Idx < Attr->args_size(); Idx++) {
3868     Expr *&E = Attr->args_begin()[Idx];
3869     assert(E && "error are handled before");
3870     if (E->isValueDependent() || E->isTypeDependent())
3871       continue;
3872 
3873     if (E->getType()->isArrayType())
3874       E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
3875                             clang::CK_ArrayToPointerDecay)
3876               .get();
3877     if (E->getType()->isFunctionType())
3878       E = ImplicitCastExpr::Create(Context,
3879                                    Context.getPointerType(E->getType()),
3880                                    clang::CK_FunctionToPointerDecay, E, nullptr,
3881                                    VK_PRValue, FPOptionsOverride());
3882     if (E->isLValue())
3883       E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(),
3884                                    clang::CK_LValueToRValue, E, nullptr,
3885                                    VK_PRValue, FPOptionsOverride());
3886 
3887     Expr::EvalResult Eval;
3888     Notes.clear();
3889     Eval.Diag = &Notes;
3890 
3891     bool Result =
3892         E->EvaluateAsConstantExpr(Eval, Context);
3893 
3894     /// Result means the expression can be folded to a constant.
3895     /// Note.empty() means the expression is a valid constant expression in the
3896     /// current language mode.
3897     if (!Result || !Notes.empty()) {
3898       Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
3899           << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
3900       for (auto &Note : Notes)
3901         Diag(Note.first, Note.second);
3902       return;
3903     }
3904     assert(Eval.Val.hasValue());
3905     E = ConstantExpr::Create(Context, E, Eval.Val);
3906   }
3907   D->addAttr(Attr);
3908 }
3909 
3910 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3911   // Make sure that there is a string literal as the annotation's first
3912   // argument.
3913   StringRef Str;
3914   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3915     return;
3916 
3917   llvm::SmallVector<Expr *, 4> Args;
3918   Args.reserve(AL.getNumArgs() - 1);
3919   for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
3920     assert(!AL.isArgIdent(Idx));
3921     Args.push_back(AL.getArgAsExpr(Idx));
3922   }
3923 
3924   S.AddAnnotationAttr(D, AL, Str, Args);
3925 }
3926 
3927 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3928   S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3929 }
3930 
3931 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
3932   AlignValueAttr TmpAttr(Context, CI, E);
3933   SourceLocation AttrLoc = CI.getLoc();
3934 
3935   QualType T;
3936   if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3937     T = TD->getUnderlyingType();
3938   else if (const auto *VD = dyn_cast<ValueDecl>(D))
3939     T = VD->getType();
3940   else
3941     llvm_unreachable("Unknown decl type for align_value");
3942 
3943   if (!T->isDependentType() && !T->isAnyPointerType() &&
3944       !T->isReferenceType() && !T->isMemberPointerType()) {
3945     Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3946       << &TmpAttr << T << D->getSourceRange();
3947     return;
3948   }
3949 
3950   if (!E->isValueDependent()) {
3951     llvm::APSInt Alignment;
3952     ExprResult ICE = VerifyIntegerConstantExpression(
3953         E, &Alignment, diag::err_align_value_attribute_argument_not_int);
3954     if (ICE.isInvalid())
3955       return;
3956 
3957     if (!Alignment.isPowerOf2()) {
3958       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3959         << E->getSourceRange();
3960       return;
3961     }
3962 
3963     D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3964     return;
3965   }
3966 
3967   // Save dependent expressions in the AST to be instantiated.
3968   D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3969 }
3970 
3971 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3972   // check the attribute arguments.
3973   if (AL.getNumArgs() > 1) {
3974     S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3975     return;
3976   }
3977 
3978   if (AL.getNumArgs() == 0) {
3979     D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3980     return;
3981   }
3982 
3983   Expr *E = AL.getArgAsExpr(0);
3984   if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3985     S.Diag(AL.getEllipsisLoc(),
3986            diag::err_pack_expansion_without_parameter_packs);
3987     return;
3988   }
3989 
3990   if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3991     return;
3992 
3993   S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3994 }
3995 
3996 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
3997                           bool IsPackExpansion) {
3998   AlignedAttr TmpAttr(Context, CI, true, E);
3999   SourceLocation AttrLoc = CI.getLoc();
4000 
4001   // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4002   if (TmpAttr.isAlignas()) {
4003     // C++11 [dcl.align]p1:
4004     //   An alignment-specifier may be applied to a variable or to a class
4005     //   data member, but it shall not be applied to a bit-field, a function
4006     //   parameter, the formal parameter of a catch clause, or a variable
4007     //   declared with the register storage class specifier. An
4008     //   alignment-specifier may also be applied to the declaration of a class
4009     //   or enumeration type.
4010     // C11 6.7.5/2:
4011     //   An alignment attribute shall not be specified in a declaration of
4012     //   a typedef, or a bit-field, or a function, or a parameter, or an
4013     //   object declared with the register storage-class specifier.
4014     int DiagKind = -1;
4015     if (isa<ParmVarDecl>(D)) {
4016       DiagKind = 0;
4017     } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
4018       if (VD->getStorageClass() == SC_Register)
4019         DiagKind = 1;
4020       if (VD->isExceptionVariable())
4021         DiagKind = 2;
4022     } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
4023       if (FD->isBitField())
4024         DiagKind = 3;
4025     } else if (!isa<TagDecl>(D)) {
4026       Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
4027         << (TmpAttr.isC11() ? ExpectedVariableOrField
4028                             : ExpectedVariableFieldOrTag);
4029       return;
4030     }
4031     if (DiagKind != -1) {
4032       Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4033         << &TmpAttr << DiagKind;
4034       return;
4035     }
4036   }
4037 
4038   if (E->isValueDependent()) {
4039     // We can't support a dependent alignment on a non-dependent type,
4040     // because we have no way to model that a type is "alignment-dependent"
4041     // but not dependent in any other way.
4042     if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4043       if (!TND->getUnderlyingType()->isDependentType()) {
4044         Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4045             << E->getSourceRange();
4046         return;
4047       }
4048     }
4049 
4050     // Save dependent expressions in the AST to be instantiated.
4051     AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4052     AA->setPackExpansion(IsPackExpansion);
4053     D->addAttr(AA);
4054     return;
4055   }
4056 
4057   // FIXME: Cache the number on the AL object?
4058   llvm::APSInt Alignment;
4059   ExprResult ICE = VerifyIntegerConstantExpression(
4060       E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4061   if (ICE.isInvalid())
4062     return;
4063 
4064   uint64_t AlignVal = Alignment.getZExtValue();
4065   // 16 byte ByVal alignment not due to a vector member is not honoured by XL
4066   // on AIX. Emit a warning here that users are generating binary incompatible
4067   // code to be safe.
4068   if (AlignVal >= 16 && isa<FieldDecl>(D) &&
4069       Context.getTargetInfo().getTriple().isOSAIX())
4070     Diag(AttrLoc, diag::warn_not_xl_compatible) << E->getSourceRange();
4071 
4072   // C++11 [dcl.align]p2:
4073   //   -- if the constant expression evaluates to zero, the alignment
4074   //      specifier shall have no effect
4075   // C11 6.7.5p6:
4076   //   An alignment specification of zero has no effect.
4077   if (!(TmpAttr.isAlignas() && !Alignment)) {
4078     if (!llvm::isPowerOf2_64(AlignVal)) {
4079       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4080         << E->getSourceRange();
4081       return;
4082     }
4083   }
4084 
4085   uint64_t MaximumAlignment = Sema::MaximumAlignment;
4086   if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4087     MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192));
4088   if (AlignVal > MaximumAlignment) {
4089     Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4090         << MaximumAlignment << E->getSourceRange();
4091     return;
4092   }
4093 
4094   const auto *VD = dyn_cast<VarDecl>(D);
4095   if (VD && Context.getTargetInfo().isTLSSupported()) {
4096     unsigned MaxTLSAlign =
4097         Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
4098             .getQuantity();
4099     if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
4100         VD->getTLSKind() != VarDecl::TLS_None) {
4101       Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4102           << (unsigned)AlignVal << VD << MaxTLSAlign;
4103       return;
4104     }
4105   }
4106 
4107   // On AIX, an aligned attribute can not decrease the alignment when applied
4108   // to a variable declaration with vector type.
4109   if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4110     const Type *Ty = VD->getType().getTypePtr();
4111     if (Ty->isVectorType() && AlignVal < 16) {
4112       Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4113           << VD->getType() << 16;
4114       return;
4115     }
4116   }
4117 
4118   AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4119   AA->setPackExpansion(IsPackExpansion);
4120   D->addAttr(AA);
4121 }
4122 
4123 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
4124                           TypeSourceInfo *TS, bool IsPackExpansion) {
4125   // FIXME: Cache the number on the AL object if non-dependent?
4126   // FIXME: Perform checking of type validity
4127   AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4128   AA->setPackExpansion(IsPackExpansion);
4129   D->addAttr(AA);
4130 }
4131 
4132 void Sema::CheckAlignasUnderalignment(Decl *D) {
4133   assert(D->hasAttrs() && "no attributes on decl");
4134 
4135   QualType UnderlyingTy, DiagTy;
4136   if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4137     UnderlyingTy = DiagTy = VD->getType();
4138   } else {
4139     UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4140     if (const auto *ED = dyn_cast<EnumDecl>(D))
4141       UnderlyingTy = ED->getIntegerType();
4142   }
4143   if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4144     return;
4145 
4146   // C++11 [dcl.align]p5, C11 6.7.5/4:
4147   //   The combined effect of all alignment attributes in a declaration shall
4148   //   not specify an alignment that is less strict than the alignment that
4149   //   would otherwise be required for the entity being declared.
4150   AlignedAttr *AlignasAttr = nullptr;
4151   AlignedAttr *LastAlignedAttr = nullptr;
4152   unsigned Align = 0;
4153   for (auto *I : D->specific_attrs<AlignedAttr>()) {
4154     if (I->isAlignmentDependent())
4155       return;
4156     if (I->isAlignas())
4157       AlignasAttr = I;
4158     Align = std::max(Align, I->getAlignment(Context));
4159     LastAlignedAttr = I;
4160   }
4161 
4162   if (Align && DiagTy->isSizelessType()) {
4163     Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4164         << LastAlignedAttr << DiagTy;
4165   } else if (AlignasAttr && Align) {
4166     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4167     CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4168     if (NaturalAlign > RequestedAlign)
4169       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4170         << DiagTy << (unsigned)NaturalAlign.getQuantity();
4171   }
4172 }
4173 
4174 bool Sema::checkMSInheritanceAttrOnDefinition(
4175     CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4176     MSInheritanceModel ExplicitModel) {
4177   assert(RD->hasDefinition() && "RD has no definition!");
4178 
4179   // We may not have seen base specifiers or any virtual methods yet.  We will
4180   // have to wait until the record is defined to catch any mismatches.
4181   if (!RD->getDefinition()->isCompleteDefinition())
4182     return false;
4183 
4184   // The unspecified model never matches what a definition could need.
4185   if (ExplicitModel == MSInheritanceModel::Unspecified)
4186     return false;
4187 
4188   if (BestCase) {
4189     if (RD->calculateInheritanceModel() == ExplicitModel)
4190       return false;
4191   } else {
4192     if (RD->calculateInheritanceModel() <= ExplicitModel)
4193       return false;
4194   }
4195 
4196   Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4197       << 0 /*definition*/;
4198   Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4199   return true;
4200 }
4201 
4202 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
4203 /// attribute.
4204 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4205                              bool &IntegerMode, bool &ComplexMode,
4206                              FloatModeKind &ExplicitType) {
4207   IntegerMode = true;
4208   ComplexMode = false;
4209   ExplicitType = FloatModeKind::NoFloat;
4210   switch (Str.size()) {
4211   case 2:
4212     switch (Str[0]) {
4213     case 'Q':
4214       DestWidth = 8;
4215       break;
4216     case 'H':
4217       DestWidth = 16;
4218       break;
4219     case 'S':
4220       DestWidth = 32;
4221       break;
4222     case 'D':
4223       DestWidth = 64;
4224       break;
4225     case 'X':
4226       DestWidth = 96;
4227       break;
4228     case 'K': // KFmode - IEEE quad precision (__float128)
4229       ExplicitType = FloatModeKind::Float128;
4230       DestWidth = Str[1] == 'I' ? 0 : 128;
4231       break;
4232     case 'T':
4233       ExplicitType = FloatModeKind::LongDouble;
4234       DestWidth = 128;
4235       break;
4236     case 'I':
4237       ExplicitType = FloatModeKind::Ibm128;
4238       DestWidth = Str[1] == 'I' ? 0 : 128;
4239       break;
4240     }
4241     if (Str[1] == 'F') {
4242       IntegerMode = false;
4243     } else if (Str[1] == 'C') {
4244       IntegerMode = false;
4245       ComplexMode = true;
4246     } else if (Str[1] != 'I') {
4247       DestWidth = 0;
4248     }
4249     break;
4250   case 4:
4251     // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4252     // pointer on PIC16 and other embedded platforms.
4253     if (Str == "word")
4254       DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4255     else if (Str == "byte")
4256       DestWidth = S.Context.getTargetInfo().getCharWidth();
4257     break;
4258   case 7:
4259     if (Str == "pointer")
4260       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
4261     break;
4262   case 11:
4263     if (Str == "unwind_word")
4264       DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4265     break;
4266   }
4267 }
4268 
4269 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4270 /// type.
4271 ///
4272 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4273 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4274 /// HImode, not an intermediate pointer.
4275 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4276   // This attribute isn't documented, but glibc uses it.  It changes
4277   // the width of an int or unsigned int to the specified size.
4278   if (!AL.isArgIdent(0)) {
4279     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4280         << AL << AANT_ArgumentIdentifier;
4281     return;
4282   }
4283 
4284   IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4285 
4286   S.AddModeAttr(D, AL, Name);
4287 }
4288 
4289 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
4290                        IdentifierInfo *Name, bool InInstantiation) {
4291   StringRef Str = Name->getName();
4292   normalizeName(Str);
4293   SourceLocation AttrLoc = CI.getLoc();
4294 
4295   unsigned DestWidth = 0;
4296   bool IntegerMode = true;
4297   bool ComplexMode = false;
4298   FloatModeKind ExplicitType = FloatModeKind::NoFloat;
4299   llvm::APInt VectorSize(64, 0);
4300   if (Str.size() >= 4 && Str[0] == 'V') {
4301     // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4302     size_t StrSize = Str.size();
4303     size_t VectorStringLength = 0;
4304     while ((VectorStringLength + 1) < StrSize &&
4305            isdigit(Str[VectorStringLength + 1]))
4306       ++VectorStringLength;
4307     if (VectorStringLength &&
4308         !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4309         VectorSize.isPowerOf2()) {
4310       parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4311                        IntegerMode, ComplexMode, ExplicitType);
4312       // Avoid duplicate warning from template instantiation.
4313       if (!InInstantiation)
4314         Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4315     } else {
4316       VectorSize = 0;
4317     }
4318   }
4319 
4320   if (!VectorSize)
4321     parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4322                      ExplicitType);
4323 
4324   // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4325   // and friends, at least with glibc.
4326   // FIXME: Make sure floating-point mappings are accurate
4327   // FIXME: Support XF and TF types
4328   if (!DestWidth) {
4329     Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4330     return;
4331   }
4332 
4333   QualType OldTy;
4334   if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4335     OldTy = TD->getUnderlyingType();
4336   else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4337     // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4338     // Try to get type from enum declaration, default to int.
4339     OldTy = ED->getIntegerType();
4340     if (OldTy.isNull())
4341       OldTy = Context.IntTy;
4342   } else
4343     OldTy = cast<ValueDecl>(D)->getType();
4344 
4345   if (OldTy->isDependentType()) {
4346     D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4347     return;
4348   }
4349 
4350   // Base type can also be a vector type (see PR17453).
4351   // Distinguish between base type and base element type.
4352   QualType OldElemTy = OldTy;
4353   if (const auto *VT = OldTy->getAs<VectorType>())
4354     OldElemTy = VT->getElementType();
4355 
4356   // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4357   // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4358   // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4359   if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4360       VectorSize.getBoolValue()) {
4361     Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4362     return;
4363   }
4364   bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4365                                 !OldElemTy->isExtIntType()) ||
4366                                OldElemTy->getAs<EnumType>();
4367 
4368   if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4369       !IntegralOrAnyEnumType)
4370     Diag(AttrLoc, diag::err_mode_not_primitive);
4371   else if (IntegerMode) {
4372     if (!IntegralOrAnyEnumType)
4373       Diag(AttrLoc, diag::err_mode_wrong_type);
4374   } else if (ComplexMode) {
4375     if (!OldElemTy->isComplexType())
4376       Diag(AttrLoc, diag::err_mode_wrong_type);
4377   } else {
4378     if (!OldElemTy->isFloatingType())
4379       Diag(AttrLoc, diag::err_mode_wrong_type);
4380   }
4381 
4382   QualType NewElemTy;
4383 
4384   if (IntegerMode)
4385     NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4386                                               OldElemTy->isSignedIntegerType());
4387   else
4388     NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
4389 
4390   if (NewElemTy.isNull()) {
4391     Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4392     return;
4393   }
4394 
4395   if (ComplexMode) {
4396     NewElemTy = Context.getComplexType(NewElemTy);
4397   }
4398 
4399   QualType NewTy = NewElemTy;
4400   if (VectorSize.getBoolValue()) {
4401     NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4402                                   VectorType::GenericVector);
4403   } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4404     // Complex machine mode does not support base vector types.
4405     if (ComplexMode) {
4406       Diag(AttrLoc, diag::err_complex_mode_vector_type);
4407       return;
4408     }
4409     unsigned NumElements = Context.getTypeSize(OldElemTy) *
4410                            OldVT->getNumElements() /
4411                            Context.getTypeSize(NewElemTy);
4412     NewTy =
4413         Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4414   }
4415 
4416   if (NewTy.isNull()) {
4417     Diag(AttrLoc, diag::err_mode_wrong_type);
4418     return;
4419   }
4420 
4421   // Install the new type.
4422   if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4423     TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4424   else if (auto *ED = dyn_cast<EnumDecl>(D))
4425     ED->setIntegerType(NewTy);
4426   else
4427     cast<ValueDecl>(D)->setType(NewTy);
4428 
4429   D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4430 }
4431 
4432 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4433   D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4434 }
4435 
4436 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4437                                               const AttributeCommonInfo &CI,
4438                                               const IdentifierInfo *Ident) {
4439   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4440     Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4441     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4442     return nullptr;
4443   }
4444 
4445   if (D->hasAttr<AlwaysInlineAttr>())
4446     return nullptr;
4447 
4448   return ::new (Context) AlwaysInlineAttr(Context, CI);
4449 }
4450 
4451 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4452                                                     const ParsedAttr &AL) {
4453   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4454     // Attribute applies to Var but not any subclass of it (like ParmVar,
4455     // ImplicitParm or VarTemplateSpecialization).
4456     if (VD->getKind() != Decl::Var) {
4457       Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4458           << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4459                                             : ExpectedVariableOrFunction);
4460       return nullptr;
4461     }
4462     // Attribute does not apply to non-static local variables.
4463     if (VD->hasLocalStorage()) {
4464       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4465       return nullptr;
4466     }
4467   }
4468 
4469   return ::new (Context) InternalLinkageAttr(Context, AL);
4470 }
4471 InternalLinkageAttr *
4472 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4473   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4474     // Attribute applies to Var but not any subclass of it (like ParmVar,
4475     // ImplicitParm or VarTemplateSpecialization).
4476     if (VD->getKind() != Decl::Var) {
4477       Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4478           << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4479                                              : ExpectedVariableOrFunction);
4480       return nullptr;
4481     }
4482     // Attribute does not apply to non-static local variables.
4483     if (VD->hasLocalStorage()) {
4484       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4485       return nullptr;
4486     }
4487   }
4488 
4489   return ::new (Context) InternalLinkageAttr(Context, AL);
4490 }
4491 
4492 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4493   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4494     Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4495     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4496     return nullptr;
4497   }
4498 
4499   if (D->hasAttr<MinSizeAttr>())
4500     return nullptr;
4501 
4502   return ::new (Context) MinSizeAttr(Context, CI);
4503 }
4504 
4505 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
4506                                         StringRef Name) {
4507   if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
4508     if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
4509       Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
4510           << PrevSNA << &SNA;
4511       Diag(SNA.getLoc(), diag::note_conflicting_attribute);
4512     }
4513 
4514     D->dropAttr<SwiftNameAttr>();
4515   }
4516   return ::new (Context) SwiftNameAttr(Context, SNA, Name);
4517 }
4518 
4519 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4520                                               const AttributeCommonInfo &CI) {
4521   if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4522     Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4523     Diag(CI.getLoc(), diag::note_conflicting_attribute);
4524     D->dropAttr<AlwaysInlineAttr>();
4525   }
4526   if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4527     Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4528     Diag(CI.getLoc(), diag::note_conflicting_attribute);
4529     D->dropAttr<MinSizeAttr>();
4530   }
4531 
4532   if (D->hasAttr<OptimizeNoneAttr>())
4533     return nullptr;
4534 
4535   return ::new (Context) OptimizeNoneAttr(Context, CI);
4536 }
4537 
4538 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4539   if (AlwaysInlineAttr *Inline =
4540           S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4541     D->addAttr(Inline);
4542 }
4543 
4544 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4545   if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4546     D->addAttr(MinSize);
4547 }
4548 
4549 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4550   if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4551     D->addAttr(Optnone);
4552 }
4553 
4554 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4555   const auto *VD = cast<VarDecl>(D);
4556   if (VD->hasLocalStorage()) {
4557     S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4558     return;
4559   }
4560   // constexpr variable may already get an implicit constant attr, which should
4561   // be replaced by the explicit constant attr.
4562   if (auto *A = D->getAttr<CUDAConstantAttr>()) {
4563     if (!A->isImplicit())
4564       return;
4565     D->dropAttr<CUDAConstantAttr>();
4566   }
4567   D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4568 }
4569 
4570 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4571   const auto *VD = cast<VarDecl>(D);
4572   // extern __shared__ is only allowed on arrays with no length (e.g.
4573   // "int x[]").
4574   if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4575       !isa<IncompleteArrayType>(VD->getType())) {
4576     S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4577     return;
4578   }
4579   if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4580       S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4581           << S.CurrentCUDATarget())
4582     return;
4583   D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4584 }
4585 
4586 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4587   const auto *FD = cast<FunctionDecl>(D);
4588   if (!FD->getReturnType()->isVoidType() &&
4589       !FD->getReturnType()->getAs<AutoType>() &&
4590       !FD->getReturnType()->isInstantiationDependentType()) {
4591     SourceRange RTRange = FD->getReturnTypeSourceRange();
4592     S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4593         << FD->getType()
4594         << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4595                               : FixItHint());
4596     return;
4597   }
4598   if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4599     if (Method->isInstance()) {
4600       S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4601           << Method;
4602       return;
4603     }
4604     S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4605   }
4606   // Only warn for "inline" when compiling for host, to cut down on noise.
4607   if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4608     S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4609 
4610   D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4611   // In host compilation the kernel is emitted as a stub function, which is
4612   // a helper function for launching the kernel. The instructions in the helper
4613   // function has nothing to do with the source code of the kernel. Do not emit
4614   // debug info for the stub function to avoid confusing the debugger.
4615   if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
4616     D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
4617 }
4618 
4619 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4620   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4621     if (VD->hasLocalStorage()) {
4622       S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4623       return;
4624     }
4625   }
4626 
4627   if (auto *A = D->getAttr<CUDADeviceAttr>()) {
4628     if (!A->isImplicit())
4629       return;
4630     D->dropAttr<CUDADeviceAttr>();
4631   }
4632   D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
4633 }
4634 
4635 static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4636   if (const auto *VD = dyn_cast<VarDecl>(D)) {
4637     if (VD->hasLocalStorage()) {
4638       S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4639       return;
4640     }
4641   }
4642   if (!D->hasAttr<HIPManagedAttr>())
4643     D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
4644   if (!D->hasAttr<CUDADeviceAttr>())
4645     D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
4646 }
4647 
4648 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4649   const auto *Fn = cast<FunctionDecl>(D);
4650   if (!Fn->isInlineSpecified()) {
4651     S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4652     return;
4653   }
4654 
4655   if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
4656     S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4657 
4658   D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4659 }
4660 
4661 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4662   if (hasDeclarator(D)) return;
4663 
4664   // Diagnostic is emitted elsewhere: here we store the (valid) AL
4665   // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4666   CallingConv CC;
4667   if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4668     return;
4669 
4670   if (!isa<ObjCMethodDecl>(D)) {
4671     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4672         << AL << ExpectedFunctionOrMethod;
4673     return;
4674   }
4675 
4676   switch (AL.getKind()) {
4677   case ParsedAttr::AT_FastCall:
4678     D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
4679     return;
4680   case ParsedAttr::AT_StdCall:
4681     D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
4682     return;
4683   case ParsedAttr::AT_ThisCall:
4684     D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
4685     return;
4686   case ParsedAttr::AT_CDecl:
4687     D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
4688     return;
4689   case ParsedAttr::AT_Pascal:
4690     D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
4691     return;
4692   case ParsedAttr::AT_SwiftCall:
4693     D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
4694     return;
4695   case ParsedAttr::AT_SwiftAsyncCall:
4696     D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
4697     return;
4698   case ParsedAttr::AT_VectorCall:
4699     D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
4700     return;
4701   case ParsedAttr::AT_MSABI:
4702     D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
4703     return;
4704   case ParsedAttr::AT_SysVABI:
4705     D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
4706     return;
4707   case ParsedAttr::AT_RegCall:
4708     D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
4709     return;
4710   case ParsedAttr::AT_Pcs: {
4711     PcsAttr::PCSType PCS;
4712     switch (CC) {
4713     case CC_AAPCS:
4714       PCS = PcsAttr::AAPCS;
4715       break;
4716     case CC_AAPCS_VFP:
4717       PCS = PcsAttr::AAPCS_VFP;
4718       break;
4719     default:
4720       llvm_unreachable("unexpected calling convention in pcs attribute");
4721     }
4722 
4723     D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
4724     return;
4725   }
4726   case ParsedAttr::AT_AArch64VectorPcs:
4727     D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
4728     return;
4729   case ParsedAttr::AT_IntelOclBicc:
4730     D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
4731     return;
4732   case ParsedAttr::AT_PreserveMost:
4733     D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
4734     return;
4735   case ParsedAttr::AT_PreserveAll:
4736     D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
4737     return;
4738   default:
4739     llvm_unreachable("unexpected attribute kind");
4740   }
4741 }
4742 
4743 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4744   if (!AL.checkAtLeastNumArgs(S, 1))
4745     return;
4746 
4747   std::vector<StringRef> DiagnosticIdentifiers;
4748   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4749     StringRef RuleName;
4750 
4751     if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4752       return;
4753 
4754     // FIXME: Warn if the rule name is unknown. This is tricky because only
4755     // clang-tidy knows about available rules.
4756     DiagnosticIdentifiers.push_back(RuleName);
4757   }
4758   D->addAttr(::new (S.Context)
4759                  SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
4760                               DiagnosticIdentifiers.size()));
4761 }
4762 
4763 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4764   TypeSourceInfo *DerefTypeLoc = nullptr;
4765   QualType ParmType;
4766   if (AL.hasParsedType()) {
4767     ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
4768 
4769     unsigned SelectIdx = ~0U;
4770     if (ParmType->isReferenceType())
4771       SelectIdx = 0;
4772     else if (ParmType->isArrayType())
4773       SelectIdx = 1;
4774 
4775     if (SelectIdx != ~0U) {
4776       S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
4777           << SelectIdx << AL;
4778       return;
4779     }
4780   }
4781 
4782   // To check if earlier decl attributes do not conflict the newly parsed ones
4783   // we always add (and check) the attribute to the canonical decl. We need
4784   // to repeat the check for attribute mutual exclusion because we're attaching
4785   // all of the attributes to the canonical declaration rather than the current
4786   // declaration.
4787   D = D->getCanonicalDecl();
4788   if (AL.getKind() == ParsedAttr::AT_Owner) {
4789     if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
4790       return;
4791     if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
4792       const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
4793                                           ? OAttr->getDerefType().getTypePtr()
4794                                           : nullptr;
4795       if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4796         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4797             << AL << OAttr;
4798         S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
4799       }
4800       return;
4801     }
4802     for (Decl *Redecl : D->redecls()) {
4803       Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
4804     }
4805   } else {
4806     if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
4807       return;
4808     if (const auto *PAttr = D->getAttr<PointerAttr>()) {
4809       const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
4810                                           ? PAttr->getDerefType().getTypePtr()
4811                                           : nullptr;
4812       if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4813         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4814             << AL << PAttr;
4815         S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
4816       }
4817       return;
4818     }
4819     for (Decl *Redecl : D->redecls()) {
4820       Redecl->addAttr(::new (S.Context)
4821                           PointerAttr(S.Context, AL, DerefTypeLoc));
4822     }
4823   }
4824 }
4825 
4826 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4827                                 const FunctionDecl *FD) {
4828   if (Attrs.isInvalid())
4829     return true;
4830 
4831   if (Attrs.hasProcessingCache()) {
4832     CC = (CallingConv) Attrs.getProcessingCache();
4833     return false;
4834   }
4835 
4836   unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4837   if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) {
4838     Attrs.setInvalid();
4839     return true;
4840   }
4841 
4842   // TODO: diagnose uses of these conventions on the wrong target.
4843   switch (Attrs.getKind()) {
4844   case ParsedAttr::AT_CDecl:
4845     CC = CC_C;
4846     break;
4847   case ParsedAttr::AT_FastCall:
4848     CC = CC_X86FastCall;
4849     break;
4850   case ParsedAttr::AT_StdCall:
4851     CC = CC_X86StdCall;
4852     break;
4853   case ParsedAttr::AT_ThisCall:
4854     CC = CC_X86ThisCall;
4855     break;
4856   case ParsedAttr::AT_Pascal:
4857     CC = CC_X86Pascal;
4858     break;
4859   case ParsedAttr::AT_SwiftCall:
4860     CC = CC_Swift;
4861     break;
4862   case ParsedAttr::AT_SwiftAsyncCall:
4863     CC = CC_SwiftAsync;
4864     break;
4865   case ParsedAttr::AT_VectorCall:
4866     CC = CC_X86VectorCall;
4867     break;
4868   case ParsedAttr::AT_AArch64VectorPcs:
4869     CC = CC_AArch64VectorCall;
4870     break;
4871   case ParsedAttr::AT_RegCall:
4872     CC = CC_X86RegCall;
4873     break;
4874   case ParsedAttr::AT_MSABI:
4875     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4876                                                              CC_Win64;
4877     break;
4878   case ParsedAttr::AT_SysVABI:
4879     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4880                                                              CC_C;
4881     break;
4882   case ParsedAttr::AT_Pcs: {
4883     StringRef StrRef;
4884     if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4885       Attrs.setInvalid();
4886       return true;
4887     }
4888     if (StrRef == "aapcs") {
4889       CC = CC_AAPCS;
4890       break;
4891     } else if (StrRef == "aapcs-vfp") {
4892       CC = CC_AAPCS_VFP;
4893       break;
4894     }
4895 
4896     Attrs.setInvalid();
4897     Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4898     return true;
4899   }
4900   case ParsedAttr::AT_IntelOclBicc:
4901     CC = CC_IntelOclBicc;
4902     break;
4903   case ParsedAttr::AT_PreserveMost:
4904     CC = CC_PreserveMost;
4905     break;
4906   case ParsedAttr::AT_PreserveAll:
4907     CC = CC_PreserveAll;
4908     break;
4909   default: llvm_unreachable("unexpected attribute kind");
4910   }
4911 
4912   TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
4913   const TargetInfo &TI = Context.getTargetInfo();
4914   // CUDA functions may have host and/or device attributes which indicate
4915   // their targeted execution environment, therefore the calling convention
4916   // of functions in CUDA should be checked against the target deduced based
4917   // on their host/device attributes.
4918   if (LangOpts.CUDA) {
4919     auto *Aux = Context.getAuxTargetInfo();
4920     auto CudaTarget = IdentifyCUDATarget(FD);
4921     bool CheckHost = false, CheckDevice = false;
4922     switch (CudaTarget) {
4923     case CFT_HostDevice:
4924       CheckHost = true;
4925       CheckDevice = true;
4926       break;
4927     case CFT_Host:
4928       CheckHost = true;
4929       break;
4930     case CFT_Device:
4931     case CFT_Global:
4932       CheckDevice = true;
4933       break;
4934     case CFT_InvalidTarget:
4935       llvm_unreachable("unexpected cuda target");
4936     }
4937     auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
4938     auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
4939     if (CheckHost && HostTI)
4940       A = HostTI->checkCallingConvention(CC);
4941     if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
4942       A = DeviceTI->checkCallingConvention(CC);
4943   } else {
4944     A = TI.checkCallingConvention(CC);
4945   }
4946 
4947   switch (A) {
4948   case TargetInfo::CCCR_OK:
4949     break;
4950 
4951   case TargetInfo::CCCR_Ignore:
4952     // Treat an ignored convention as if it was an explicit C calling convention
4953     // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
4954     // that command line flags that change the default convention to
4955     // __vectorcall don't affect declarations marked __stdcall.
4956     CC = CC_C;
4957     break;
4958 
4959   case TargetInfo::CCCR_Error:
4960     Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
4961         << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4962     break;
4963 
4964   case TargetInfo::CCCR_Warning: {
4965     Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
4966         << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4967 
4968     // This convention is not valid for the target. Use the default function or
4969     // method calling convention.
4970     bool IsCXXMethod = false, IsVariadic = false;
4971     if (FD) {
4972       IsCXXMethod = FD->isCXXInstanceMember();
4973       IsVariadic = FD->isVariadic();
4974     }
4975     CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4976     break;
4977   }
4978   }
4979 
4980   Attrs.setProcessingCache((unsigned) CC);
4981   return false;
4982 }
4983 
4984 /// Pointer-like types in the default address space.
4985 static bool isValidSwiftContextType(QualType Ty) {
4986   if (!Ty->hasPointerRepresentation())
4987     return Ty->isDependentType();
4988   return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4989 }
4990 
4991 /// Pointers and references in the default address space.
4992 static bool isValidSwiftIndirectResultType(QualType Ty) {
4993   if (const auto *PtrType = Ty->getAs<PointerType>()) {
4994     Ty = PtrType->getPointeeType();
4995   } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4996     Ty = RefType->getPointeeType();
4997   } else {
4998     return Ty->isDependentType();
4999   }
5000   return Ty.getAddressSpace() == LangAS::Default;
5001 }
5002 
5003 /// Pointers and references to pointers in the default address space.
5004 static bool isValidSwiftErrorResultType(QualType Ty) {
5005   if (const auto *PtrType = Ty->getAs<PointerType>()) {
5006     Ty = PtrType->getPointeeType();
5007   } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5008     Ty = RefType->getPointeeType();
5009   } else {
5010     return Ty->isDependentType();
5011   }
5012   if (!Ty.getQualifiers().empty())
5013     return false;
5014   return isValidSwiftContextType(Ty);
5015 }
5016 
5017 void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
5018                                ParameterABI abi) {
5019 
5020   QualType type = cast<ParmVarDecl>(D)->getType();
5021 
5022   if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
5023     if (existingAttr->getABI() != abi) {
5024       Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
5025           << getParameterABISpelling(abi) << existingAttr;
5026       Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
5027       return;
5028     }
5029   }
5030 
5031   switch (abi) {
5032   case ParameterABI::Ordinary:
5033     llvm_unreachable("explicit attribute for ordinary parameter ABI?");
5034 
5035   case ParameterABI::SwiftContext:
5036     if (!isValidSwiftContextType(type)) {
5037       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5038           << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5039     }
5040     D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
5041     return;
5042 
5043   case ParameterABI::SwiftAsyncContext:
5044     if (!isValidSwiftContextType(type)) {
5045       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5046           << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5047     }
5048     D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI));
5049     return;
5050 
5051   case ParameterABI::SwiftErrorResult:
5052     if (!isValidSwiftErrorResultType(type)) {
5053       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5054           << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
5055     }
5056     D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
5057     return;
5058 
5059   case ParameterABI::SwiftIndirectResult:
5060     if (!isValidSwiftIndirectResultType(type)) {
5061       Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5062           << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
5063     }
5064     D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
5065     return;
5066   }
5067   llvm_unreachable("bad parameter ABI attribute");
5068 }
5069 
5070 /// Checks a regparm attribute, returning true if it is ill-formed and
5071 /// otherwise setting numParams to the appropriate value.
5072 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
5073   if (AL.isInvalid())
5074     return true;
5075 
5076   if (!AL.checkExactlyNumArgs(*this, 1)) {
5077     AL.setInvalid();
5078     return true;
5079   }
5080 
5081   uint32_t NP;
5082   Expr *NumParamsExpr = AL.getArgAsExpr(0);
5083   if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
5084     AL.setInvalid();
5085     return true;
5086   }
5087 
5088   if (Context.getTargetInfo().getRegParmMax() == 0) {
5089     Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
5090       << NumParamsExpr->getSourceRange();
5091     AL.setInvalid();
5092     return true;
5093   }
5094 
5095   numParams = NP;
5096   if (numParams > Context.getTargetInfo().getRegParmMax()) {
5097     Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
5098       << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
5099     AL.setInvalid();
5100     return true;
5101   }
5102 
5103   return false;
5104 }
5105 
5106 // Checks whether an argument of launch_bounds attribute is
5107 // acceptable, performs implicit conversion to Rvalue, and returns
5108 // non-nullptr Expr result on success. Otherwise, it returns nullptr
5109 // and may output an error.
5110 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
5111                                      const CUDALaunchBoundsAttr &AL,
5112                                      const unsigned Idx) {
5113   if (S.DiagnoseUnexpandedParameterPack(E))
5114     return nullptr;
5115 
5116   // Accept template arguments for now as they depend on something else.
5117   // We'll get to check them when they eventually get instantiated.
5118   if (E->isValueDependent())
5119     return E;
5120 
5121   Optional<llvm::APSInt> I = llvm::APSInt(64);
5122   if (!(I = E->getIntegerConstantExpr(S.Context))) {
5123     S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
5124         << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
5125     return nullptr;
5126   }
5127   // Make sure we can fit it in 32 bits.
5128   if (!I->isIntN(32)) {
5129     S.Diag(E->getExprLoc(), diag::err_ice_too_large)
5130         << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
5131     return nullptr;
5132   }
5133   if (*I < 0)
5134     S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
5135         << &AL << Idx << E->getSourceRange();
5136 
5137   // We may need to perform implicit conversion of the argument.
5138   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5139       S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
5140   ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
5141   assert(!ValArg.isInvalid() &&
5142          "Unexpected PerformCopyInitialization() failure.");
5143 
5144   return ValArg.getAs<Expr>();
5145 }
5146 
5147 void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5148                                Expr *MaxThreads, Expr *MinBlocks) {
5149   CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks);
5150   MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
5151   if (MaxThreads == nullptr)
5152     return;
5153 
5154   if (MinBlocks) {
5155     MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
5156     if (MinBlocks == nullptr)
5157       return;
5158   }
5159 
5160   D->addAttr(::new (Context)
5161                  CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks));
5162 }
5163 
5164 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5165   if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
5166     return;
5167 
5168   S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
5169                         AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr);
5170 }
5171 
5172 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
5173                                           const ParsedAttr &AL) {
5174   if (!AL.isArgIdent(0)) {
5175     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5176         << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
5177     return;
5178   }
5179 
5180   ParamIdx ArgumentIdx;
5181   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
5182                                            ArgumentIdx))
5183     return;
5184 
5185   ParamIdx TypeTagIdx;
5186   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
5187                                            TypeTagIdx))
5188     return;
5189 
5190   bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
5191   if (IsPointer) {
5192     // Ensure that buffer has a pointer type.
5193     unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
5194     if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
5195         !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
5196       S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
5197   }
5198 
5199   D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
5200       S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
5201       IsPointer));
5202 }
5203 
5204 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
5205                                          const ParsedAttr &AL) {
5206   if (!AL.isArgIdent(0)) {
5207     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5208         << AL << 1 << AANT_ArgumentIdentifier;
5209     return;
5210   }
5211 
5212   if (!AL.checkExactlyNumArgs(S, 1))
5213     return;
5214 
5215   if (!isa<VarDecl>(D)) {
5216     S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
5217         << AL << ExpectedVariable;
5218     return;
5219   }
5220 
5221   IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
5222   TypeSourceInfo *MatchingCTypeLoc = nullptr;
5223   S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
5224   assert(MatchingCTypeLoc && "no type source info for attribute argument");
5225 
5226   D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
5227       S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
5228       AL.getMustBeNull()));
5229 }
5230 
5231 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5232   ParamIdx ArgCount;
5233 
5234   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
5235                                            ArgCount,
5236                                            true /* CanIndexImplicitThis */))
5237     return;
5238 
5239   // ArgCount isn't a parameter index [0;n), it's a count [1;n]
5240   D->addAttr(::new (S.Context)
5241                  XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
5242 }
5243 
5244 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
5245                                              const ParsedAttr &AL) {
5246   uint32_t Count = 0, Offset = 0;
5247   if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
5248     return;
5249   if (AL.getNumArgs() == 2) {
5250     Expr *Arg = AL.getArgAsExpr(1);
5251     if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
5252       return;
5253     if (Count < Offset) {
5254       S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
5255           << &AL << 0 << Count << Arg->getBeginLoc();
5256       return;
5257     }
5258   }
5259   D->addAttr(::new (S.Context)
5260                  PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
5261 }
5262 
5263 namespace {
5264 struct IntrinToName {
5265   uint32_t Id;
5266   int32_t FullName;
5267   int32_t ShortName;
5268 };
5269 } // unnamed namespace
5270 
5271 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
5272                                  ArrayRef<IntrinToName> Map,
5273                                  const char *IntrinNames) {
5274   if (AliasName.startswith("__arm_"))
5275     AliasName = AliasName.substr(6);
5276   const IntrinToName *It = std::lower_bound(
5277       Map.begin(), Map.end(), BuiltinID,
5278       [](const IntrinToName &L, unsigned Id) { return L.Id < Id; });
5279   if (It == Map.end() || It->Id != BuiltinID)
5280     return false;
5281   StringRef FullName(&IntrinNames[It->FullName]);
5282   if (AliasName == FullName)
5283     return true;
5284   if (It->ShortName == -1)
5285     return false;
5286   StringRef ShortName(&IntrinNames[It->ShortName]);
5287   return AliasName == ShortName;
5288 }
5289 
5290 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5291 #include "clang/Basic/arm_mve_builtin_aliases.inc"
5292   // The included file defines:
5293   // - ArrayRef<IntrinToName> Map
5294   // - const char IntrinNames[]
5295   return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5296 }
5297 
5298 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
5299 #include "clang/Basic/arm_cde_builtin_aliases.inc"
5300   return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5301 }
5302 
5303 static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID,
5304                              StringRef AliasName) {
5305   if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
5306     BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
5307   return BuiltinID >= AArch64::FirstSVEBuiltin &&
5308          BuiltinID <= AArch64::LastSVEBuiltin;
5309 }
5310 
5311 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5312   if (!AL.isArgIdent(0)) {
5313     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5314         << AL << 1 << AANT_ArgumentIdentifier;
5315     return;
5316   }
5317 
5318   IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5319   unsigned BuiltinID = Ident->getBuiltinID();
5320   StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5321 
5322   bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5323   if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) ||
5324       (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) &&
5325        !ArmCdeAliasValid(BuiltinID, AliasName))) {
5326     S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
5327     return;
5328   }
5329 
5330   D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
5331 }
5332 
5333 static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) {
5334   return BuiltinID >= Builtin::FirstTSBuiltin &&
5335          BuiltinID < RISCV::LastTSBuiltin;
5336 }
5337 
5338 static void handleBuiltinAliasAttr(Sema &S, Decl *D,
5339                                         const ParsedAttr &AL) {
5340   if (!AL.isArgIdent(0)) {
5341     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5342         << AL << 1 << AANT_ArgumentIdentifier;
5343     return;
5344   }
5345 
5346   IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5347   unsigned BuiltinID = Ident->getBuiltinID();
5348   StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5349 
5350   bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5351   bool IsARM = S.Context.getTargetInfo().getTriple().isARM();
5352   bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV();
5353   if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) ||
5354       (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) &&
5355        !ArmCdeAliasValid(BuiltinID, AliasName)) ||
5356       (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) ||
5357       (!IsAArch64 && !IsARM && !IsRISCV)) {
5358     S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL;
5359     return;
5360   }
5361 
5362   D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
5363 }
5364 
5365 //===----------------------------------------------------------------------===//
5366 // Checker-specific attribute handlers.
5367 //===----------------------------------------------------------------------===//
5368 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
5369   return QT->isDependentType() || QT->isObjCRetainableType();
5370 }
5371 
5372 static bool isValidSubjectOfNSAttribute(QualType QT) {
5373   return QT->isDependentType() || QT->isObjCObjectPointerType() ||
5374          QT->isObjCNSObjectType();
5375 }
5376 
5377 static bool isValidSubjectOfCFAttribute(QualType QT) {
5378   return QT->isDependentType() || QT->isPointerType() ||
5379          isValidSubjectOfNSAttribute(QT);
5380 }
5381 
5382 static bool isValidSubjectOfOSAttribute(QualType QT) {
5383   if (QT->isDependentType())
5384     return true;
5385   QualType PT = QT->getPointeeType();
5386   return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
5387 }
5388 
5389 void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
5390                             RetainOwnershipKind K,
5391                             bool IsTemplateInstantiation) {
5392   ValueDecl *VD = cast<ValueDecl>(D);
5393   switch (K) {
5394   case RetainOwnershipKind::OS:
5395     handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
5396         *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
5397         diag::warn_ns_attribute_wrong_parameter_type,
5398         /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
5399     return;
5400   case RetainOwnershipKind::NS:
5401     handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
5402         *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
5403 
5404         // These attributes are normally just advisory, but in ARC, ns_consumed
5405         // is significant.  Allow non-dependent code to contain inappropriate
5406         // attributes even in ARC, but require template instantiations to be
5407         // set up correctly.
5408         ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
5409              ? diag::err_ns_attribute_wrong_parameter_type
5410              : diag::warn_ns_attribute_wrong_parameter_type),
5411         /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
5412     return;
5413   case RetainOwnershipKind::CF:
5414     handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
5415         *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
5416         diag::warn_ns_attribute_wrong_parameter_type,
5417         /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
5418     return;
5419   }
5420 }
5421 
5422 static Sema::RetainOwnershipKind
5423 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
5424   switch (AL.getKind()) {
5425   case ParsedAttr::AT_CFConsumed:
5426   case ParsedAttr::AT_CFReturnsRetained:
5427   case ParsedAttr::AT_CFReturnsNotRetained:
5428     return Sema::RetainOwnershipKind::CF;
5429   case ParsedAttr::AT_OSConsumesThis:
5430   case ParsedAttr::AT_OSConsumed:
5431   case ParsedAttr::AT_OSReturnsRetained:
5432   case ParsedAttr::AT_OSReturnsNotRetained:
5433   case ParsedAttr::AT_OSReturnsRetainedOnZero:
5434   case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
5435     return Sema::RetainOwnershipKind::OS;
5436   case ParsedAttr::AT_NSConsumesSelf:
5437   case ParsedAttr::AT_NSConsumed:
5438   case ParsedAttr::AT_NSReturnsRetained:
5439   case ParsedAttr::AT_NSReturnsNotRetained:
5440   case ParsedAttr::AT_NSReturnsAutoreleased:
5441     return Sema::RetainOwnershipKind::NS;
5442   default:
5443     llvm_unreachable("Wrong argument supplied");
5444   }
5445 }
5446 
5447 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
5448   if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
5449     return false;
5450 
5451   Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
5452       << "'ns_returns_retained'" << 0 << 0;
5453   return true;
5454 }
5455 
5456 /// \return whether the parameter is a pointer to OSObject pointer.
5457 static bool isValidOSObjectOutParameter(const Decl *D) {
5458   const auto *PVD = dyn_cast<ParmVarDecl>(D);
5459   if (!PVD)
5460     return false;
5461   QualType QT = PVD->getType();
5462   QualType PT = QT->getPointeeType();
5463   return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
5464 }
5465 
5466 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
5467                                         const ParsedAttr &AL) {
5468   QualType ReturnType;
5469   Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
5470 
5471   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5472     ReturnType = MD->getReturnType();
5473   } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
5474              (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
5475     return; // ignore: was handled as a type attribute
5476   } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
5477     ReturnType = PD->getType();
5478   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5479     ReturnType = FD->getReturnType();
5480   } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
5481     // Attributes on parameters are used for out-parameters,
5482     // passed as pointers-to-pointers.
5483     unsigned DiagID = K == Sema::RetainOwnershipKind::CF
5484             ? /*pointer-to-CF-pointer*/2
5485             : /*pointer-to-OSObject-pointer*/3;
5486     ReturnType = Param->getType()->getPointeeType();
5487     if (ReturnType.isNull()) {
5488       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5489           << AL << DiagID << AL.getRange();
5490       return;
5491     }
5492   } else if (AL.isUsedAsTypeAttr()) {
5493     return;
5494   } else {
5495     AttributeDeclKind ExpectedDeclKind;
5496     switch (AL.getKind()) {
5497     default: llvm_unreachable("invalid ownership attribute");
5498     case ParsedAttr::AT_NSReturnsRetained:
5499     case ParsedAttr::AT_NSReturnsAutoreleased:
5500     case ParsedAttr::AT_NSReturnsNotRetained:
5501       ExpectedDeclKind = ExpectedFunctionOrMethod;
5502       break;
5503 
5504     case ParsedAttr::AT_OSReturnsRetained:
5505     case ParsedAttr::AT_OSReturnsNotRetained:
5506     case ParsedAttr::AT_CFReturnsRetained:
5507     case ParsedAttr::AT_CFReturnsNotRetained:
5508       ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
5509       break;
5510     }
5511     S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
5512         << AL.getRange() << AL << ExpectedDeclKind;
5513     return;
5514   }
5515 
5516   bool TypeOK;
5517   bool Cf;
5518   unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
5519   switch (AL.getKind()) {
5520   default: llvm_unreachable("invalid ownership attribute");
5521   case ParsedAttr::AT_NSReturnsRetained:
5522     TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
5523     Cf = false;
5524     break;
5525 
5526   case ParsedAttr::AT_NSReturnsAutoreleased:
5527   case ParsedAttr::AT_NSReturnsNotRetained:
5528     TypeOK = isValidSubjectOfNSAttribute(ReturnType);
5529     Cf = false;
5530     break;
5531 
5532   case ParsedAttr::AT_CFReturnsRetained:
5533   case ParsedAttr::AT_CFReturnsNotRetained:
5534     TypeOK = isValidSubjectOfCFAttribute(ReturnType);
5535     Cf = true;
5536     break;
5537 
5538   case ParsedAttr::AT_OSReturnsRetained:
5539   case ParsedAttr::AT_OSReturnsNotRetained:
5540     TypeOK = isValidSubjectOfOSAttribute(ReturnType);
5541     Cf = true;
5542     ParmDiagID = 3; // Pointer-to-OSObject-pointer
5543     break;
5544   }
5545 
5546   if (!TypeOK) {
5547     if (AL.isUsedAsTypeAttr())
5548       return;
5549 
5550     if (isa<ParmVarDecl>(D)) {
5551       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5552           << AL << ParmDiagID << AL.getRange();
5553     } else {
5554       // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
5555       enum : unsigned {
5556         Function,
5557         Method,
5558         Property
5559       } SubjectKind = Function;
5560       if (isa<ObjCMethodDecl>(D))
5561         SubjectKind = Method;
5562       else if (isa<ObjCPropertyDecl>(D))
5563         SubjectKind = Property;
5564       S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5565           << AL << SubjectKind << Cf << AL.getRange();
5566     }
5567     return;
5568   }
5569 
5570   switch (AL.getKind()) {
5571     default:
5572       llvm_unreachable("invalid ownership attribute");
5573     case ParsedAttr::AT_NSReturnsAutoreleased:
5574       handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
5575       return;
5576     case ParsedAttr::AT_CFReturnsNotRetained:
5577       handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
5578       return;
5579     case ParsedAttr::AT_NSReturnsNotRetained:
5580       handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
5581       return;
5582     case ParsedAttr::AT_CFReturnsRetained:
5583       handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
5584       return;
5585     case ParsedAttr::AT_NSReturnsRetained:
5586       handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
5587       return;
5588     case ParsedAttr::AT_OSReturnsRetained:
5589       handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5590       return;
5591     case ParsedAttr::AT_OSReturnsNotRetained:
5592       handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5593       return;
5594   };
5595 }
5596 
5597 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5598                                               const ParsedAttr &Attrs) {
5599   const int EP_ObjCMethod = 1;
5600   const int EP_ObjCProperty = 2;
5601 
5602   SourceLocation loc = Attrs.getLoc();
5603   QualType resultType;
5604   if (isa<ObjCMethodDecl>(D))
5605     resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5606   else
5607     resultType = cast<ObjCPropertyDecl>(D)->getType();
5608 
5609   if (!resultType->isReferenceType() &&
5610       (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5611     S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5612         << SourceRange(loc) << Attrs
5613         << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5614         << /*non-retainable pointer*/ 2;
5615 
5616     // Drop the attribute.
5617     return;
5618   }
5619 
5620   D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
5621 }
5622 
5623 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5624                                         const ParsedAttr &Attrs) {
5625   const auto *Method = cast<ObjCMethodDecl>(D);
5626 
5627   const DeclContext *DC = Method->getDeclContext();
5628   if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5629     S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5630                                                                       << 0;
5631     S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5632     return;
5633   }
5634   if (Method->getMethodFamily() == OMF_dealloc) {
5635     S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5636                                                                       << 1;
5637     return;
5638   }
5639 
5640   D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
5641 }
5642 
5643 static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &AL) {
5644   auto *E = AL.getArgAsExpr(0);
5645   auto Loc = E ? E->getBeginLoc() : AL.getLoc();
5646 
5647   auto *DRE = dyn_cast<DeclRefExpr>(AL.getArgAsExpr(0));
5648   if (!DRE) {
5649     S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
5650     return;
5651   }
5652 
5653   auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
5654   if (!VD) {
5655     S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 1 << DRE->getDecl();
5656     return;
5657   }
5658 
5659   if (!isNSStringType(VD->getType(), S.Context) &&
5660       !isCFStringType(VD->getType(), S.Context)) {
5661     S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD;
5662     return;
5663   }
5664 
5665   D->addAttr(::new (S.Context) NSErrorDomainAttr(S.Context, AL, VD));
5666 }
5667 
5668 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5669   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5670 
5671   if (!Parm) {
5672     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5673     return;
5674   }
5675 
5676   // Typedefs only allow objc_bridge(id) and have some additional checking.
5677   if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5678     if (!Parm->Ident->isStr("id")) {
5679       S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5680       return;
5681     }
5682 
5683     // Only allow 'cv void *'.
5684     QualType T = TD->getUnderlyingType();
5685     if (!T->isVoidPointerType()) {
5686       S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5687       return;
5688     }
5689   }
5690 
5691   D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
5692 }
5693 
5694 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5695                                         const ParsedAttr &AL) {
5696   IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5697 
5698   if (!Parm) {
5699     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5700     return;
5701   }
5702 
5703   D->addAttr(::new (S.Context)
5704                  ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
5705 }
5706 
5707 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5708                                         const ParsedAttr &AL) {
5709   IdentifierInfo *RelatedClass =
5710       AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5711   if (!RelatedClass) {
5712     S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5713     return;
5714   }
5715   IdentifierInfo *ClassMethod =
5716     AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5717   IdentifierInfo *InstanceMethod =
5718     AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5719   D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
5720       S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
5721 }
5722 
5723 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5724                                             const ParsedAttr &AL) {
5725   DeclContext *Ctx = D->getDeclContext();
5726 
5727   // This attribute can only be applied to methods in interfaces or class
5728   // extensions.
5729   if (!isa<ObjCInterfaceDecl>(Ctx) &&
5730       !(isa<ObjCCategoryDecl>(Ctx) &&
5731         cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5732     S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5733     return;
5734   }
5735 
5736   ObjCInterfaceDecl *IFace;
5737   if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5738     IFace = CatDecl->getClassInterface();
5739   else
5740     IFace = cast<ObjCInterfaceDecl>(Ctx);
5741 
5742   if (!IFace)
5743     return;
5744 
5745   IFace->setHasDesignatedInitializers();
5746   D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
5747 }
5748 
5749 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5750   StringRef MetaDataName;
5751   if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5752     return;
5753   D->addAttr(::new (S.Context)
5754                  ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
5755 }
5756 
5757 // When a user wants to use objc_boxable with a union or struct
5758 // but they don't have access to the declaration (legacy/third-party code)
5759 // then they can 'enable' this feature with a typedef:
5760 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5761 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5762   bool notify = false;
5763 
5764   auto *RD = dyn_cast<RecordDecl>(D);
5765   if (RD && RD->getDefinition()) {
5766     RD = RD->getDefinition();
5767     notify = true;
5768   }
5769 
5770   if (RD) {
5771     ObjCBoxableAttr *BoxableAttr =
5772         ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
5773     RD->addAttr(BoxableAttr);
5774     if (notify) {
5775       // we need to notify ASTReader/ASTWriter about
5776       // modification of existing declaration
5777       if (ASTMutationListener *L = S.getASTMutationListener())
5778         L->AddedAttributeToRecord(BoxableAttr, RD);
5779     }
5780   }
5781 }
5782 
5783 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5784   if (hasDeclarator(D)) return;
5785 
5786   S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5787       << AL.getRange() << AL << ExpectedVariable;
5788 }
5789 
5790 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5791                                           const ParsedAttr &AL) {
5792   const auto *VD = cast<ValueDecl>(D);
5793   QualType QT = VD->getType();
5794 
5795   if (!QT->isDependentType() &&
5796       !QT->isObjCLifetimeType()) {
5797     S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5798       << QT;
5799     return;
5800   }
5801 
5802   Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5803 
5804   // If we have no lifetime yet, check the lifetime we're presumably
5805   // going to infer.
5806   if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5807     Lifetime = QT->getObjCARCImplicitLifetime();
5808 
5809   switch (Lifetime) {
5810   case Qualifiers::OCL_None:
5811     assert(QT->isDependentType() &&
5812            "didn't infer lifetime for non-dependent type?");
5813     break;
5814 
5815   case Qualifiers::OCL_Weak:   // meaningful
5816   case Qualifiers::OCL_Strong: // meaningful
5817     break;
5818 
5819   case Qualifiers::OCL_ExplicitNone:
5820   case Qualifiers::OCL_Autoreleasing:
5821     S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5822         << (Lifetime == Qualifiers::OCL_Autoreleasing);
5823     break;
5824   }
5825 
5826   D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
5827 }
5828 
5829 static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5830   // Make sure that there is a string literal as the annotation's single
5831   // argument.
5832   StringRef Str;
5833   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
5834     return;
5835 
5836   D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str));
5837 }
5838 
5839 static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) {
5840   // Make sure that there is a string literal as the annotation's single
5841   // argument.
5842   StringRef BT;
5843   if (!S.checkStringLiteralArgumentAttr(AL, 0, BT))
5844     return;
5845 
5846   // Warn about duplicate attributes if they have different arguments, but drop
5847   // any duplicate attributes regardless.
5848   if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) {
5849     if (Other->getSwiftType() != BT)
5850       S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
5851     return;
5852   }
5853 
5854   D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT));
5855 }
5856 
5857 static bool isErrorParameter(Sema &S, QualType QT) {
5858   const auto *PT = QT->getAs<PointerType>();
5859   if (!PT)
5860     return false;
5861 
5862   QualType Pointee = PT->getPointeeType();
5863 
5864   // Check for NSError**.
5865   if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>())
5866     if (const auto *ID = OPT->getInterfaceDecl())
5867       if (ID->getIdentifier() == S.getNSErrorIdent())
5868         return true;
5869 
5870   // Check for CFError**.
5871   if (const auto *PT = Pointee->getAs<PointerType>())
5872     if (const auto *RT = PT->getPointeeType()->getAs<RecordType>())
5873       if (S.isCFError(RT->getDecl()))
5874         return true;
5875 
5876   return false;
5877 }
5878 
5879 static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) {
5880   auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
5881     for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
5882       if (isErrorParameter(S, getFunctionOrMethodParamType(D, I)))
5883         return true;
5884     }
5885 
5886     S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter)
5887         << AL << isa<ObjCMethodDecl>(D);
5888     return false;
5889   };
5890 
5891   auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
5892     // - C, ObjC, and block pointers are definitely okay.
5893     // - References are definitely not okay.
5894     // - nullptr_t is weird, but acceptable.
5895     QualType RT = getFunctionOrMethodResultType(D);
5896     if (RT->hasPointerRepresentation() && !RT->isReferenceType())
5897       return true;
5898 
5899     S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
5900         << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
5901         << /*pointer*/ 1;
5902     return false;
5903   };
5904 
5905   auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
5906     QualType RT = getFunctionOrMethodResultType(D);
5907     if (RT->isIntegralType(S.Context))
5908       return true;
5909 
5910     S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
5911         << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
5912         << /*integral*/ 0;
5913     return false;
5914   };
5915 
5916   if (D->isInvalidDecl())
5917     return;
5918 
5919   IdentifierLoc *Loc = AL.getArgAsIdent(0);
5920   SwiftErrorAttr::ConventionKind Convention;
5921   if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(),
5922                                                   Convention)) {
5923     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5924         << AL << Loc->Ident;
5925     return;
5926   }
5927 
5928   switch (Convention) {
5929   case SwiftErrorAttr::None:
5930     // No additional validation required.
5931     break;
5932 
5933   case SwiftErrorAttr::NonNullError:
5934     if (!hasErrorParameter(S, D, AL))
5935       return;
5936     break;
5937 
5938   case SwiftErrorAttr::NullResult:
5939     if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL))
5940       return;
5941     break;
5942 
5943   case SwiftErrorAttr::NonZeroResult:
5944   case SwiftErrorAttr::ZeroResult:
5945     if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL))
5946       return;
5947     break;
5948   }
5949 
5950   D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention));
5951 }
5952 
5953 static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D,
5954                                       const SwiftAsyncErrorAttr *ErrorAttr,
5955                                       const SwiftAsyncAttr *AsyncAttr) {
5956   if (AsyncAttr->getKind() == SwiftAsyncAttr::None) {
5957     if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) {
5958       S.Diag(AsyncAttr->getLocation(),
5959              diag::err_swift_async_error_without_swift_async)
5960           << AsyncAttr << isa<ObjCMethodDecl>(D);
5961     }
5962     return;
5963   }
5964 
5965   const ParmVarDecl *HandlerParam = getFunctionOrMethodParam(
5966       D, AsyncAttr->getCompletionHandlerIndex().getASTIndex());
5967   // handleSwiftAsyncAttr already verified the type is correct, so no need to
5968   // double-check it here.
5969   const auto *FuncTy = HandlerParam->getType()
5970                            ->castAs<BlockPointerType>()
5971                            ->getPointeeType()
5972                            ->getAs<FunctionProtoType>();
5973   ArrayRef<QualType> BlockParams;
5974   if (FuncTy)
5975     BlockParams = FuncTy->getParamTypes();
5976 
5977   switch (ErrorAttr->getConvention()) {
5978   case SwiftAsyncErrorAttr::ZeroArgument:
5979   case SwiftAsyncErrorAttr::NonZeroArgument: {
5980     uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx();
5981     if (ParamIdx == 0 || ParamIdx > BlockParams.size()) {
5982       S.Diag(ErrorAttr->getLocation(),
5983              diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2;
5984       return;
5985     }
5986     QualType ErrorParam = BlockParams[ParamIdx - 1];
5987     if (!ErrorParam->isIntegralType(S.Context)) {
5988       StringRef ConvStr =
5989           ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument
5990               ? "zero_argument"
5991               : "nonzero_argument";
5992       S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral)
5993           << ErrorAttr << ConvStr << ParamIdx << ErrorParam;
5994       return;
5995     }
5996     break;
5997   }
5998   case SwiftAsyncErrorAttr::NonNullError: {
5999     bool AnyErrorParams = false;
6000     for (QualType Param : BlockParams) {
6001       // Check for NSError *.
6002       if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) {
6003         if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) {
6004           if (ID->getIdentifier() == S.getNSErrorIdent()) {
6005             AnyErrorParams = true;
6006             break;
6007           }
6008         }
6009       }
6010       // Check for CFError *.
6011       if (const auto *PtrTy = Param->getAs<PointerType>()) {
6012         if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) {
6013           if (S.isCFError(RT->getDecl())) {
6014             AnyErrorParams = true;
6015             break;
6016           }
6017         }
6018       }
6019     }
6020 
6021     if (!AnyErrorParams) {
6022       S.Diag(ErrorAttr->getLocation(),
6023              diag::err_swift_async_error_no_error_parameter)
6024           << ErrorAttr << isa<ObjCMethodDecl>(D);
6025       return;
6026     }
6027     break;
6028   }
6029   case SwiftAsyncErrorAttr::None:
6030     break;
6031   }
6032 }
6033 
6034 static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) {
6035   IdentifierLoc *IDLoc = AL.getArgAsIdent(0);
6036   SwiftAsyncErrorAttr::ConventionKind ConvKind;
6037   if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(),
6038                                                        ConvKind)) {
6039     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6040         << AL << IDLoc->Ident;
6041     return;
6042   }
6043 
6044   uint32_t ParamIdx = 0;
6045   switch (ConvKind) {
6046   case SwiftAsyncErrorAttr::ZeroArgument:
6047   case SwiftAsyncErrorAttr::NonZeroArgument: {
6048     if (!AL.checkExactlyNumArgs(S, 2))
6049       return;
6050 
6051     Expr *IdxExpr = AL.getArgAsExpr(1);
6052     if (!checkUInt32Argument(S, AL, IdxExpr, ParamIdx))
6053       return;
6054     break;
6055   }
6056   case SwiftAsyncErrorAttr::NonNullError:
6057   case SwiftAsyncErrorAttr::None: {
6058     if (!AL.checkExactlyNumArgs(S, 1))
6059       return;
6060     break;
6061   }
6062   }
6063 
6064   auto *ErrorAttr =
6065       ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx);
6066   D->addAttr(ErrorAttr);
6067 
6068   if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>())
6069     checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
6070 }
6071 
6072 // For a function, this will validate a compound Swift name, e.g.
6073 // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
6074 // the function will output the number of parameter names, and whether this is a
6075 // single-arg initializer.
6076 //
6077 // For a type, enum constant, property, or variable declaration, this will
6078 // validate either a simple identifier, or a qualified
6079 // <code>context.identifier</code> name.
6080 static bool
6081 validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc,
6082                           StringRef Name, unsigned &SwiftParamCount,
6083                           bool &IsSingleParamInit) {
6084   SwiftParamCount = 0;
6085   IsSingleParamInit = false;
6086 
6087   // Check whether this will be mapped to a getter or setter of a property.
6088   bool IsGetter = false, IsSetter = false;
6089   if (Name.startswith("getter:")) {
6090     IsGetter = true;
6091     Name = Name.substr(7);
6092   } else if (Name.startswith("setter:")) {
6093     IsSetter = true;
6094     Name = Name.substr(7);
6095   }
6096 
6097   if (Name.back() != ')') {
6098     S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6099     return false;
6100   }
6101 
6102   bool IsMember = false;
6103   StringRef ContextName, BaseName, Parameters;
6104 
6105   std::tie(BaseName, Parameters) = Name.split('(');
6106 
6107   // Split at the first '.', if it exists, which separates the context name
6108   // from the base name.
6109   std::tie(ContextName, BaseName) = BaseName.split('.');
6110   if (BaseName.empty()) {
6111     BaseName = ContextName;
6112     ContextName = StringRef();
6113   } else if (ContextName.empty() || !isValidAsciiIdentifier(ContextName)) {
6114     S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6115         << AL << /*context*/ 1;
6116     return false;
6117   } else {
6118     IsMember = true;
6119   }
6120 
6121   if (!isValidAsciiIdentifier(BaseName) || BaseName == "_") {
6122     S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6123         << AL << /*basename*/ 0;
6124     return false;
6125   }
6126 
6127   bool IsSubscript = BaseName == "subscript";
6128   // A subscript accessor must be a getter or setter.
6129   if (IsSubscript && !IsGetter && !IsSetter) {
6130     S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6131         << AL << /* getter or setter */ 0;
6132     return false;
6133   }
6134 
6135   if (Parameters.empty()) {
6136     S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL;
6137     return false;
6138   }
6139 
6140   assert(Parameters.back() == ')' && "expected ')'");
6141   Parameters = Parameters.drop_back(); // ')'
6142 
6143   if (Parameters.empty()) {
6144     // Setters and subscripts must have at least one parameter.
6145     if (IsSubscript) {
6146       S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6147           << AL << /* have at least one parameter */1;
6148       return false;
6149     }
6150 
6151     if (IsSetter) {
6152       S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL;
6153       return false;
6154     }
6155 
6156     return true;
6157   }
6158 
6159   if (Parameters.back() != ':') {
6160     S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6161     return false;
6162   }
6163 
6164   StringRef CurrentParam;
6165   llvm::Optional<unsigned> SelfLocation;
6166   unsigned NewValueCount = 0;
6167   llvm::Optional<unsigned> NewValueLocation;
6168   do {
6169     std::tie(CurrentParam, Parameters) = Parameters.split(':');
6170 
6171     if (!isValidAsciiIdentifier(CurrentParam)) {
6172       S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6173           << AL << /*parameter*/2;
6174       return false;
6175     }
6176 
6177     if (IsMember && CurrentParam == "self") {
6178       // "self" indicates the "self" argument for a member.
6179 
6180       // More than one "self"?
6181       if (SelfLocation) {
6182         S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL;
6183         return false;
6184       }
6185 
6186       // The "self" location is the current parameter.
6187       SelfLocation = SwiftParamCount;
6188     } else if (CurrentParam == "newValue") {
6189       // "newValue" indicates the "newValue" argument for a setter.
6190 
6191       // There should only be one 'newValue', but it's only significant for
6192       // subscript accessors, so don't error right away.
6193       ++NewValueCount;
6194 
6195       NewValueLocation = SwiftParamCount;
6196     }
6197 
6198     ++SwiftParamCount;
6199   } while (!Parameters.empty());
6200 
6201   // Only instance subscripts are currently supported.
6202   if (IsSubscript && !SelfLocation) {
6203     S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6204         << AL << /*have a 'self:' parameter*/2;
6205     return false;
6206   }
6207 
6208   IsSingleParamInit =
6209         SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_";
6210 
6211   // Check the number of parameters for a getter/setter.
6212   if (IsGetter || IsSetter) {
6213     // Setters have one parameter for the new value.
6214     unsigned NumExpectedParams = IsGetter ? 0 : 1;
6215     unsigned ParamDiag =
6216         IsGetter ? diag::warn_attr_swift_name_getter_parameters
6217                  : diag::warn_attr_swift_name_setter_parameters;
6218 
6219     // Instance methods have one parameter for "self".
6220     if (SelfLocation)
6221       ++NumExpectedParams;
6222 
6223     // Subscripts may have additional parameters beyond the expected params for
6224     // the index.
6225     if (IsSubscript) {
6226       if (SwiftParamCount < NumExpectedParams) {
6227         S.Diag(Loc, ParamDiag) << AL;
6228         return false;
6229       }
6230 
6231       // A subscript setter must explicitly label its newValue parameter to
6232       // distinguish it from index parameters.
6233       if (IsSetter) {
6234         if (!NewValueLocation) {
6235           S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue)
6236               << AL;
6237           return false;
6238         }
6239         if (NewValueCount > 1) {
6240           S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues)
6241               << AL;
6242           return false;
6243         }
6244       } else {
6245         // Subscript getters should have no 'newValue:' parameter.
6246         if (NewValueLocation) {
6247           S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue)
6248               << AL;
6249           return false;
6250         }
6251       }
6252     } else {
6253       // Property accessors must have exactly the number of expected params.
6254       if (SwiftParamCount != NumExpectedParams) {
6255         S.Diag(Loc, ParamDiag) << AL;
6256         return false;
6257       }
6258     }
6259   }
6260 
6261   return true;
6262 }
6263 
6264 bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
6265                              const ParsedAttr &AL, bool IsAsync) {
6266   if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
6267     ArrayRef<ParmVarDecl*> Params;
6268     unsigned ParamCount;
6269 
6270     if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) {
6271       ParamCount = Method->getSelector().getNumArgs();
6272       Params = Method->parameters().slice(0, ParamCount);
6273     } else {
6274       const auto *F = cast<FunctionDecl>(D);
6275 
6276       ParamCount = F->getNumParams();
6277       Params = F->parameters();
6278 
6279       if (!F->hasWrittenPrototype()) {
6280         Diag(Loc, diag::warn_attribute_wrong_decl_type) << AL
6281             << ExpectedFunctionWithProtoType;
6282         return false;
6283       }
6284     }
6285 
6286     // The async name drops the last callback parameter.
6287     if (IsAsync) {
6288       if (ParamCount == 0) {
6289         Diag(Loc, diag::warn_attr_swift_name_decl_missing_params)
6290             << AL << isa<ObjCMethodDecl>(D);
6291         return false;
6292       }
6293       ParamCount -= 1;
6294     }
6295 
6296     unsigned SwiftParamCount;
6297     bool IsSingleParamInit;
6298     if (!validateSwiftFunctionName(*this, AL, Loc, Name,
6299                                    SwiftParamCount, IsSingleParamInit))
6300       return false;
6301 
6302     bool ParamCountValid;
6303     if (SwiftParamCount == ParamCount) {
6304       ParamCountValid = true;
6305     } else if (SwiftParamCount > ParamCount) {
6306       ParamCountValid = IsSingleParamInit && ParamCount == 0;
6307     } else {
6308       // We have fewer Swift parameters than Objective-C parameters, but that
6309       // might be because we've transformed some of them. Check for potential
6310       // "out" parameters and err on the side of not warning.
6311       unsigned MaybeOutParamCount =
6312           std::count_if(Params.begin(), Params.end(),
6313                         [](const ParmVarDecl *Param) -> bool {
6314         QualType ParamTy = Param->getType();
6315         if (ParamTy->isReferenceType() || ParamTy->isPointerType())
6316           return !ParamTy->getPointeeType().isConstQualified();
6317         return false;
6318       });
6319 
6320       ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount;
6321     }
6322 
6323     if (!ParamCountValid) {
6324       Diag(Loc, diag::warn_attr_swift_name_num_params)
6325           << (SwiftParamCount > ParamCount) << AL << ParamCount
6326           << SwiftParamCount;
6327       return false;
6328     }
6329   } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) ||
6330               isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) ||
6331               isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) ||
6332               isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) &&
6333              !IsAsync) {
6334     StringRef ContextName, BaseName;
6335 
6336     std::tie(ContextName, BaseName) = Name.split('.');
6337     if (BaseName.empty()) {
6338       BaseName = ContextName;
6339       ContextName = StringRef();
6340     } else if (!isValidAsciiIdentifier(ContextName)) {
6341       Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6342           << /*context*/1;
6343       return false;
6344     }
6345 
6346     if (!isValidAsciiIdentifier(BaseName)) {
6347       Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6348           << /*basename*/0;
6349       return false;
6350     }
6351   } else {
6352     Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL;
6353     return false;
6354   }
6355   return true;
6356 }
6357 
6358 static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) {
6359   StringRef Name;
6360   SourceLocation Loc;
6361   if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6362     return;
6363 
6364   if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false))
6365     return;
6366 
6367   D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name));
6368 }
6369 
6370 static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) {
6371   StringRef Name;
6372   SourceLocation Loc;
6373   if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6374     return;
6375 
6376   if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true))
6377     return;
6378 
6379   D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name));
6380 }
6381 
6382 static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) {
6383   // Make sure that there is an identifier as the annotation's single argument.
6384   if (!AL.checkExactlyNumArgs(S, 1))
6385     return;
6386 
6387   if (!AL.isArgIdent(0)) {
6388     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6389         << AL << AANT_ArgumentIdentifier;
6390     return;
6391   }
6392 
6393   SwiftNewTypeAttr::NewtypeKind Kind;
6394   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6395   if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) {
6396     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
6397     return;
6398   }
6399 
6400   if (!isa<TypedefNameDecl>(D)) {
6401     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
6402         << AL << "typedefs";
6403     return;
6404   }
6405 
6406   D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind));
6407 }
6408 
6409 static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6410   if (!AL.isArgIdent(0)) {
6411     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
6412         << AL << 1 << AANT_ArgumentIdentifier;
6413     return;
6414   }
6415 
6416   SwiftAsyncAttr::Kind Kind;
6417   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6418   if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) {
6419     S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II;
6420     return;
6421   }
6422 
6423   ParamIdx Idx;
6424   if (Kind == SwiftAsyncAttr::None) {
6425     // If this is 'none', then there shouldn't be any additional arguments.
6426     if (!AL.checkExactlyNumArgs(S, 1))
6427       return;
6428   } else {
6429     // Non-none swift_async requires a completion handler index argument.
6430     if (!AL.checkExactlyNumArgs(S, 2))
6431       return;
6432 
6433     Expr *HandlerIdx = AL.getArgAsExpr(1);
6434     if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx))
6435       return;
6436 
6437     const ParmVarDecl *CompletionBlock =
6438         getFunctionOrMethodParam(D, Idx.getASTIndex());
6439     QualType CompletionBlockType = CompletionBlock->getType();
6440     if (!CompletionBlockType->isBlockPointerType()) {
6441       S.Diag(CompletionBlock->getLocation(),
6442              diag::err_swift_async_bad_block_type)
6443           << CompletionBlock->getType();
6444       return;
6445     }
6446     QualType BlockTy =
6447         CompletionBlockType->castAs<BlockPointerType>()->getPointeeType();
6448     if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) {
6449       S.Diag(CompletionBlock->getLocation(),
6450              diag::err_swift_async_bad_block_type)
6451           << CompletionBlock->getType();
6452       return;
6453     }
6454   }
6455 
6456   auto *AsyncAttr =
6457       ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx);
6458   D->addAttr(AsyncAttr);
6459 
6460   if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>())
6461     checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
6462 }
6463 
6464 //===----------------------------------------------------------------------===//
6465 // Microsoft specific attribute handlers.
6466 //===----------------------------------------------------------------------===//
6467 
6468 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
6469                               StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
6470   if (const auto *UA = D->getAttr<UuidAttr>()) {
6471     if (declaresSameEntity(UA->getGuidDecl(), GuidDecl))
6472       return nullptr;
6473     if (!UA->getGuid().empty()) {
6474       Diag(UA->getLocation(), diag::err_mismatched_uuid);
6475       Diag(CI.getLoc(), diag::note_previous_uuid);
6476       D->dropAttr<UuidAttr>();
6477     }
6478   }
6479 
6480   return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
6481 }
6482 
6483 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6484   if (!S.LangOpts.CPlusPlus) {
6485     S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
6486         << AL << AttributeLangSupport::C;
6487     return;
6488   }
6489 
6490   StringRef OrigStrRef;
6491   SourceLocation LiteralLoc;
6492   if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc))
6493     return;
6494 
6495   // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
6496   // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
6497   StringRef StrRef = OrigStrRef;
6498   if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
6499     StrRef = StrRef.drop_front().drop_back();
6500 
6501   // Validate GUID length.
6502   if (StrRef.size() != 36) {
6503     S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
6504     return;
6505   }
6506 
6507   for (unsigned i = 0; i < 36; ++i) {
6508     if (i == 8 || i == 13 || i == 18 || i == 23) {
6509       if (StrRef[i] != '-') {
6510         S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
6511         return;
6512       }
6513     } else if (!isHexDigit(StrRef[i])) {
6514       S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
6515       return;
6516     }
6517   }
6518 
6519   // Convert to our parsed format and canonicalize.
6520   MSGuidDecl::Parts Parsed;
6521   StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1);
6522   StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2);
6523   StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3);
6524   for (unsigned i = 0; i != 8; ++i)
6525     StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2)
6526         .getAsInteger(16, Parsed.Part4And5[i]);
6527   MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed);
6528 
6529   // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
6530   // the only thing in the [] list, the [] too), and add an insertion of
6531   // __declspec(uuid(...)).  But sadly, neither the SourceLocs of the commas
6532   // separating attributes nor of the [ and the ] are in the AST.
6533   // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
6534   // on cfe-dev.
6535   if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
6536     S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
6537 
6538   UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid);
6539   if (UA)
6540     D->addAttr(UA);
6541 }
6542 
6543 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6544   if (!S.LangOpts.CPlusPlus) {
6545     S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
6546         << AL << AttributeLangSupport::C;
6547     return;
6548   }
6549   MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
6550       D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
6551   if (IA) {
6552     D->addAttr(IA);
6553     S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
6554   }
6555 }
6556 
6557 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6558   const auto *VD = cast<VarDecl>(D);
6559   if (!S.Context.getTargetInfo().isTLSSupported()) {
6560     S.Diag(AL.getLoc(), diag::err_thread_unsupported);
6561     return;
6562   }
6563   if (VD->getTSCSpec() != TSCS_unspecified) {
6564     S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
6565     return;
6566   }
6567   if (VD->hasLocalStorage()) {
6568     S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
6569     return;
6570   }
6571   D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
6572 }
6573 
6574 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6575   SmallVector<StringRef, 4> Tags;
6576   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6577     StringRef Tag;
6578     if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
6579       return;
6580     Tags.push_back(Tag);
6581   }
6582 
6583   if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
6584     if (!NS->isInline()) {
6585       S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
6586       return;
6587     }
6588     if (NS->isAnonymousNamespace()) {
6589       S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
6590       return;
6591     }
6592     if (AL.getNumArgs() == 0)
6593       Tags.push_back(NS->getName());
6594   } else if (!AL.checkAtLeastNumArgs(S, 1))
6595     return;
6596 
6597   // Store tags sorted and without duplicates.
6598   llvm::sort(Tags);
6599   Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
6600 
6601   D->addAttr(::new (S.Context)
6602                  AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
6603 }
6604 
6605 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6606   // Check the attribute arguments.
6607   if (AL.getNumArgs() > 1) {
6608     S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
6609     return;
6610   }
6611 
6612   StringRef Str;
6613   SourceLocation ArgLoc;
6614 
6615   if (AL.getNumArgs() == 0)
6616     Str = "";
6617   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6618     return;
6619 
6620   ARMInterruptAttr::InterruptType Kind;
6621   if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
6622     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
6623                                                                  << ArgLoc;
6624     return;
6625   }
6626 
6627   D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
6628 }
6629 
6630 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6631   // MSP430 'interrupt' attribute is applied to
6632   // a function with no parameters and void return type.
6633   if (!isFunctionOrMethod(D)) {
6634     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6635         << "'interrupt'" << ExpectedFunctionOrMethod;
6636     return;
6637   }
6638 
6639   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
6640     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6641         << /*MSP430*/ 1 << 0;
6642     return;
6643   }
6644 
6645   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6646     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6647         << /*MSP430*/ 1 << 1;
6648     return;
6649   }
6650 
6651   // The attribute takes one integer argument.
6652   if (!AL.checkExactlyNumArgs(S, 1))
6653     return;
6654 
6655   if (!AL.isArgExpr(0)) {
6656     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6657         << AL << AANT_ArgumentIntegerConstant;
6658     return;
6659   }
6660 
6661   Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
6662   Optional<llvm::APSInt> NumParams = llvm::APSInt(32);
6663   if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) {
6664     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6665         << AL << AANT_ArgumentIntegerConstant
6666         << NumParamsExpr->getSourceRange();
6667     return;
6668   }
6669   // The argument should be in range 0..63.
6670   unsigned Num = NumParams->getLimitedValue(255);
6671   if (Num > 63) {
6672     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
6673         << AL << (int)NumParams->getSExtValue()
6674         << NumParamsExpr->getSourceRange();
6675     return;
6676   }
6677 
6678   D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
6679   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6680 }
6681 
6682 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6683   // Only one optional argument permitted.
6684   if (AL.getNumArgs() > 1) {
6685     S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
6686     return;
6687   }
6688 
6689   StringRef Str;
6690   SourceLocation ArgLoc;
6691 
6692   if (AL.getNumArgs() == 0)
6693     Str = "";
6694   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6695     return;
6696 
6697   // Semantic checks for a function with the 'interrupt' attribute for MIPS:
6698   // a) Must be a function.
6699   // b) Must have no parameters.
6700   // c) Must have the 'void' return type.
6701   // d) Cannot have the 'mips16' attribute, as that instruction set
6702   //    lacks the 'eret' instruction.
6703   // e) The attribute itself must either have no argument or one of the
6704   //    valid interrupt types, see [MipsInterruptDocs].
6705 
6706   if (!isFunctionOrMethod(D)) {
6707     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6708         << "'interrupt'" << ExpectedFunctionOrMethod;
6709     return;
6710   }
6711 
6712   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
6713     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6714         << /*MIPS*/ 0 << 0;
6715     return;
6716   }
6717 
6718   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6719     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
6720         << /*MIPS*/ 0 << 1;
6721     return;
6722   }
6723 
6724   // We still have to do this manually because the Interrupt attributes are
6725   // a bit special due to sharing their spellings across targets.
6726   if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
6727     return;
6728 
6729   MipsInterruptAttr::InterruptType Kind;
6730   if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
6731     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6732         << AL << "'" + std::string(Str) + "'";
6733     return;
6734   }
6735 
6736   D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
6737 }
6738 
6739 static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6740   if (!AL.checkExactlyNumArgs(S, 1))
6741     return;
6742 
6743   if (!AL.isArgExpr(0)) {
6744     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6745         << AL << AANT_ArgumentIntegerConstant;
6746     return;
6747   }
6748 
6749   // FIXME: Check for decl - it should be void ()(void).
6750 
6751   Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
6752   auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(S.Context);
6753   if (!MaybeNumParams) {
6754     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6755         << AL << AANT_ArgumentIntegerConstant
6756         << NumParamsExpr->getSourceRange();
6757     return;
6758   }
6759 
6760   unsigned Num = MaybeNumParams->getLimitedValue(255);
6761   if ((Num & 1) || Num > 30) {
6762     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
6763         << AL << (int)MaybeNumParams->getSExtValue()
6764         << NumParamsExpr->getSourceRange();
6765     return;
6766   }
6767 
6768   D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num));
6769   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6770 }
6771 
6772 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6773   // Semantic checks for a function with the 'interrupt' attribute.
6774   // a) Must be a function.
6775   // b) Must have the 'void' return type.
6776   // c) Must take 1 or 2 arguments.
6777   // d) The 1st argument must be a pointer.
6778   // e) The 2nd argument (if any) must be an unsigned integer.
6779   if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
6780       CXXMethodDecl::isStaticOverloadedOperator(
6781           cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
6782     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
6783         << AL << ExpectedFunctionWithProtoType;
6784     return;
6785   }
6786   // Interrupt handler must have void return type.
6787   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
6788     S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
6789            diag::err_anyx86_interrupt_attribute)
6790         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6791                 ? 0
6792                 : 1)
6793         << 0;
6794     return;
6795   }
6796   // Interrupt handler must have 1 or 2 parameters.
6797   unsigned NumParams = getFunctionOrMethodNumParams(D);
6798   if (NumParams < 1 || NumParams > 2) {
6799     S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
6800         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6801                 ? 0
6802                 : 1)
6803         << 1;
6804     return;
6805   }
6806   // The first argument must be a pointer.
6807   if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
6808     S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
6809            diag::err_anyx86_interrupt_attribute)
6810         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6811                 ? 0
6812                 : 1)
6813         << 2;
6814     return;
6815   }
6816   // The second argument, if present, must be an unsigned integer.
6817   unsigned TypeSize =
6818       S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
6819           ? 64
6820           : 32;
6821   if (NumParams == 2 &&
6822       (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
6823        S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
6824     S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
6825            diag::err_anyx86_interrupt_attribute)
6826         << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
6827                 ? 0
6828                 : 1)
6829         << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
6830     return;
6831   }
6832   D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
6833   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6834 }
6835 
6836 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6837   if (!isFunctionOrMethod(D)) {
6838     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6839         << "'interrupt'" << ExpectedFunction;
6840     return;
6841   }
6842 
6843   if (!AL.checkExactlyNumArgs(S, 0))
6844     return;
6845 
6846   handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
6847 }
6848 
6849 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6850   if (!isFunctionOrMethod(D)) {
6851     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6852         << "'signal'" << ExpectedFunction;
6853     return;
6854   }
6855 
6856   if (!AL.checkExactlyNumArgs(S, 0))
6857     return;
6858 
6859   handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
6860 }
6861 
6862 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
6863   // Add preserve_access_index attribute to all fields and inner records.
6864   for (auto D : RD->decls()) {
6865     if (D->hasAttr<BPFPreserveAccessIndexAttr>())
6866       continue;
6867 
6868     D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
6869     if (auto *Rec = dyn_cast<RecordDecl>(D))
6870       handleBPFPreserveAIRecord(S, Rec);
6871   }
6872 }
6873 
6874 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
6875     const ParsedAttr &AL) {
6876   auto *Rec = cast<RecordDecl>(D);
6877   handleBPFPreserveAIRecord(S, Rec);
6878   Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
6879 }
6880 
6881 static bool hasBTFTagAttr(Decl *D, StringRef Tag) {
6882   for (const auto *I : D->specific_attrs<BTFTagAttr>()) {
6883     if (I->getBTFTag() == Tag)
6884       return true;
6885   }
6886   return false;
6887 }
6888 
6889 static void handleBTFTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6890   StringRef Str;
6891   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
6892     return;
6893   if (hasBTFTagAttr(D, Str))
6894     return;
6895 
6896   D->addAttr(::new (S.Context) BTFTagAttr(S.Context, AL, Str));
6897 }
6898 
6899 BTFTagAttr *Sema::mergeBTFTagAttr(Decl *D, const BTFTagAttr &AL) {
6900   if (hasBTFTagAttr(D, AL.getBTFTag()))
6901     return nullptr;
6902   return ::new (Context) BTFTagAttr(Context, AL, AL.getBTFTag());
6903 }
6904 
6905 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6906   if (!isFunctionOrMethod(D)) {
6907     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
6908         << "'export_name'" << ExpectedFunction;
6909     return;
6910   }
6911 
6912   auto *FD = cast<FunctionDecl>(D);
6913   if (FD->isThisDeclarationADefinition()) {
6914     S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
6915     return;
6916   }
6917 
6918   StringRef Str;
6919   SourceLocation ArgLoc;
6920   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6921     return;
6922 
6923   D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
6924   D->addAttr(UsedAttr::CreateImplicit(S.Context));
6925 }
6926 
6927 WebAssemblyImportModuleAttr *
6928 Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) {
6929   auto *FD = cast<FunctionDecl>(D);
6930 
6931   if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
6932     if (ExistingAttr->getImportModule() == AL.getImportModule())
6933       return nullptr;
6934     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0
6935       << ExistingAttr->getImportModule() << AL.getImportModule();
6936     Diag(AL.getLoc(), diag::note_previous_attribute);
6937     return nullptr;
6938   }
6939   if (FD->hasBody()) {
6940     Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
6941     return nullptr;
6942   }
6943   return ::new (Context) WebAssemblyImportModuleAttr(Context, AL,
6944                                                      AL.getImportModule());
6945 }
6946 
6947 WebAssemblyImportNameAttr *
6948 Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) {
6949   auto *FD = cast<FunctionDecl>(D);
6950 
6951   if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) {
6952     if (ExistingAttr->getImportName() == AL.getImportName())
6953       return nullptr;
6954     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1
6955       << ExistingAttr->getImportName() << AL.getImportName();
6956     Diag(AL.getLoc(), diag::note_previous_attribute);
6957     return nullptr;
6958   }
6959   if (FD->hasBody()) {
6960     Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
6961     return nullptr;
6962   }
6963   return ::new (Context) WebAssemblyImportNameAttr(Context, AL,
6964                                                    AL.getImportName());
6965 }
6966 
6967 static void
6968 handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6969   auto *FD = cast<FunctionDecl>(D);
6970 
6971   StringRef Str;
6972   SourceLocation ArgLoc;
6973   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6974     return;
6975   if (FD->hasBody()) {
6976     S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
6977     return;
6978   }
6979 
6980   FD->addAttr(::new (S.Context)
6981                   WebAssemblyImportModuleAttr(S.Context, AL, Str));
6982 }
6983 
6984 static void
6985 handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6986   auto *FD = cast<FunctionDecl>(D);
6987 
6988   StringRef Str;
6989   SourceLocation ArgLoc;
6990   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
6991     return;
6992   if (FD->hasBody()) {
6993     S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
6994     return;
6995   }
6996 
6997   FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
6998 }
6999 
7000 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
7001                                      const ParsedAttr &AL) {
7002   // Warn about repeated attributes.
7003   if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
7004     S.Diag(AL.getRange().getBegin(),
7005       diag::warn_riscv_repeated_interrupt_attribute);
7006     S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
7007     return;
7008   }
7009 
7010   // Check the attribute argument. Argument is optional.
7011   if (!AL.checkAtMostNumArgs(S, 1))
7012     return;
7013 
7014   StringRef Str;
7015   SourceLocation ArgLoc;
7016 
7017   // 'machine'is the default interrupt mode.
7018   if (AL.getNumArgs() == 0)
7019     Str = "machine";
7020   else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7021     return;
7022 
7023   // Semantic checks for a function with the 'interrupt' attribute:
7024   // - Must be a function.
7025   // - Must have no parameters.
7026   // - Must have the 'void' return type.
7027   // - The attribute itself must either have no argument or one of the
7028   //   valid interrupt types, see [RISCVInterruptDocs].
7029 
7030   if (D->getFunctionType() == nullptr) {
7031     S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7032       << "'interrupt'" << ExpectedFunction;
7033     return;
7034   }
7035 
7036   if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7037     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7038       << /*RISC-V*/ 2 << 0;
7039     return;
7040   }
7041 
7042   if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7043     S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7044       << /*RISC-V*/ 2 << 1;
7045     return;
7046   }
7047 
7048   RISCVInterruptAttr::InterruptType Kind;
7049   if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7050     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
7051                                                                  << ArgLoc;
7052     return;
7053   }
7054 
7055   D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
7056 }
7057 
7058 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7059   // Dispatch the interrupt attribute based on the current target.
7060   switch (S.Context.getTargetInfo().getTriple().getArch()) {
7061   case llvm::Triple::msp430:
7062     handleMSP430InterruptAttr(S, D, AL);
7063     break;
7064   case llvm::Triple::mipsel:
7065   case llvm::Triple::mips:
7066     handleMipsInterruptAttr(S, D, AL);
7067     break;
7068   case llvm::Triple::m68k:
7069     handleM68kInterruptAttr(S, D, AL);
7070     break;
7071   case llvm::Triple::x86:
7072   case llvm::Triple::x86_64:
7073     handleAnyX86InterruptAttr(S, D, AL);
7074     break;
7075   case llvm::Triple::avr:
7076     handleAVRInterruptAttr(S, D, AL);
7077     break;
7078   case llvm::Triple::riscv32:
7079   case llvm::Triple::riscv64:
7080     handleRISCVInterruptAttr(S, D, AL);
7081     break;
7082   default:
7083     handleARMInterruptAttr(S, D, AL);
7084     break;
7085   }
7086 }
7087 
7088 static bool
7089 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
7090                                       const AMDGPUFlatWorkGroupSizeAttr &Attr) {
7091   // Accept template arguments for now as they depend on something else.
7092   // We'll get to check them when they eventually get instantiated.
7093   if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
7094     return false;
7095 
7096   uint32_t Min = 0;
7097   if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
7098     return true;
7099 
7100   uint32_t Max = 0;
7101   if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
7102     return true;
7103 
7104   if (Min == 0 && Max != 0) {
7105     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7106         << &Attr << 0;
7107     return true;
7108   }
7109   if (Min > Max) {
7110     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7111         << &Attr << 1;
7112     return true;
7113   }
7114 
7115   return false;
7116 }
7117 
7118 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
7119                                           const AttributeCommonInfo &CI,
7120                                           Expr *MinExpr, Expr *MaxExpr) {
7121   AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
7122 
7123   if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
7124     return;
7125 
7126   D->addAttr(::new (Context)
7127                  AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr));
7128 }
7129 
7130 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
7131                                               const ParsedAttr &AL) {
7132   Expr *MinExpr = AL.getArgAsExpr(0);
7133   Expr *MaxExpr = AL.getArgAsExpr(1);
7134 
7135   S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
7136 }
7137 
7138 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
7139                                            Expr *MaxExpr,
7140                                            const AMDGPUWavesPerEUAttr &Attr) {
7141   if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
7142       (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
7143     return true;
7144 
7145   // Accept template arguments for now as they depend on something else.
7146   // We'll get to check them when they eventually get instantiated.
7147   if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
7148     return false;
7149 
7150   uint32_t Min = 0;
7151   if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
7152     return true;
7153 
7154   uint32_t Max = 0;
7155   if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
7156     return true;
7157 
7158   if (Min == 0 && Max != 0) {
7159     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7160         << &Attr << 0;
7161     return true;
7162   }
7163   if (Max != 0 && Min > Max) {
7164     S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7165         << &Attr << 1;
7166     return true;
7167   }
7168 
7169   return false;
7170 }
7171 
7172 void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
7173                                    Expr *MinExpr, Expr *MaxExpr) {
7174   AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
7175 
7176   if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
7177     return;
7178 
7179   D->addAttr(::new (Context)
7180                  AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr));
7181 }
7182 
7183 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7184   if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
7185     return;
7186 
7187   Expr *MinExpr = AL.getArgAsExpr(0);
7188   Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
7189 
7190   S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
7191 }
7192 
7193 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7194   uint32_t NumSGPR = 0;
7195   Expr *NumSGPRExpr = AL.getArgAsExpr(0);
7196   if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
7197     return;
7198 
7199   D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
7200 }
7201 
7202 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7203   uint32_t NumVGPR = 0;
7204   Expr *NumVGPRExpr = AL.getArgAsExpr(0);
7205   if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
7206     return;
7207 
7208   D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
7209 }
7210 
7211 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
7212                                               const ParsedAttr &AL) {
7213   // If we try to apply it to a function pointer, don't warn, but don't
7214   // do anything, either. It doesn't matter anyway, because there's nothing
7215   // special about calling a force_align_arg_pointer function.
7216   const auto *VD = dyn_cast<ValueDecl>(D);
7217   if (VD && VD->getType()->isFunctionPointerType())
7218     return;
7219   // Also don't warn on function pointer typedefs.
7220   const auto *TD = dyn_cast<TypedefNameDecl>(D);
7221   if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
7222     TD->getUnderlyingType()->isFunctionType()))
7223     return;
7224   // Attribute can only be applied to function types.
7225   if (!isa<FunctionDecl>(D)) {
7226     S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
7227         << AL << ExpectedFunction;
7228     return;
7229   }
7230 
7231   D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
7232 }
7233 
7234 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
7235   uint32_t Version;
7236   Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
7237   if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
7238     return;
7239 
7240   // TODO: Investigate what happens with the next major version of MSVC.
7241   if (Version != LangOptions::MSVC2015 / 100) {
7242     S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
7243         << AL << Version << VersionExpr->getSourceRange();
7244     return;
7245   }
7246 
7247   // The attribute expects a "major" version number like 19, but new versions of
7248   // MSVC have moved to updating the "minor", or less significant numbers, so we
7249   // have to multiply by 100 now.
7250   Version *= 100;
7251 
7252   D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
7253 }
7254 
7255 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
7256                                         const AttributeCommonInfo &CI) {
7257   if (D->hasAttr<DLLExportAttr>()) {
7258     Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
7259     return nullptr;
7260   }
7261 
7262   if (D->hasAttr<DLLImportAttr>())
7263     return nullptr;
7264 
7265   return ::new (Context) DLLImportAttr(Context, CI);
7266 }
7267 
7268 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
7269                                         const AttributeCommonInfo &CI) {
7270   if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
7271     Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
7272     D->dropAttr<DLLImportAttr>();
7273   }
7274 
7275   if (D->hasAttr<DLLExportAttr>())
7276     return nullptr;
7277 
7278   return ::new (Context) DLLExportAttr(Context, CI);
7279 }
7280 
7281 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
7282   if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
7283       (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
7284     S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
7285     return;
7286   }
7287 
7288   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7289     if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
7290         !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
7291       // MinGW doesn't allow dllimport on inline functions.
7292       S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
7293           << A;
7294       return;
7295     }
7296   }
7297 
7298   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
7299     if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) &&
7300         MD->getParent()->isLambda()) {
7301       S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
7302       return;
7303     }
7304   }
7305 
7306   Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
7307                       ? (Attr *)S.mergeDLLExportAttr(D, A)
7308                       : (Attr *)S.mergeDLLImportAttr(D, A);
7309   if (NewAttr)
7310     D->addAttr(NewAttr);
7311 }
7312 
7313 MSInheritanceAttr *
7314 Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
7315                              bool BestCase,
7316                              MSInheritanceModel Model) {
7317   if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
7318     if (IA->getInheritanceModel() == Model)
7319       return nullptr;
7320     Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
7321         << 1 /*previous declaration*/;
7322     Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
7323     D->dropAttr<MSInheritanceAttr>();
7324   }
7325 
7326   auto *RD = cast<CXXRecordDecl>(D);
7327   if (RD->hasDefinition()) {
7328     if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
7329                                            Model)) {
7330       return nullptr;
7331     }
7332   } else {
7333     if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
7334       Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
7335           << 1 /*partial specialization*/;
7336       return nullptr;
7337     }
7338     if (RD->getDescribedClassTemplate()) {
7339       Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
7340           << 0 /*primary template*/;
7341       return nullptr;
7342     }
7343   }
7344 
7345   return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
7346 }
7347 
7348 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7349   // The capability attributes take a single string parameter for the name of
7350   // the capability they represent. The lockable attribute does not take any
7351   // parameters. However, semantically, both attributes represent the same
7352   // concept, and so they use the same semantic attribute. Eventually, the
7353   // lockable attribute will be removed.
7354   //
7355   // For backward compatibility, any capability which has no specified string
7356   // literal will be considered a "mutex."
7357   StringRef N("mutex");
7358   SourceLocation LiteralLoc;
7359   if (AL.getKind() == ParsedAttr::AT_Capability &&
7360       !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
7361     return;
7362 
7363   D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
7364 }
7365 
7366 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7367   SmallVector<Expr*, 1> Args;
7368   if (!checkLockFunAttrCommon(S, D, AL, Args))
7369     return;
7370 
7371   D->addAttr(::new (S.Context)
7372                  AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
7373 }
7374 
7375 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
7376                                         const ParsedAttr &AL) {
7377   SmallVector<Expr*, 1> Args;
7378   if (!checkLockFunAttrCommon(S, D, AL, Args))
7379     return;
7380 
7381   D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
7382                                                      Args.size()));
7383 }
7384 
7385 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
7386                                            const ParsedAttr &AL) {
7387   SmallVector<Expr*, 2> Args;
7388   if (!checkTryLockFunAttrCommon(S, D, AL, Args))
7389     return;
7390 
7391   D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
7392       S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
7393 }
7394 
7395 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
7396                                         const ParsedAttr &AL) {
7397   // Check that all arguments are lockable objects.
7398   SmallVector<Expr *, 1> Args;
7399   checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
7400 
7401   D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
7402                                                      Args.size()));
7403 }
7404 
7405 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
7406                                          const ParsedAttr &AL) {
7407   if (!AL.checkAtLeastNumArgs(S, 1))
7408     return;
7409 
7410   // check that all arguments are lockable objects
7411   SmallVector<Expr*, 1> Args;
7412   checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
7413   if (Args.empty())
7414     return;
7415 
7416   RequiresCapabilityAttr *RCA = ::new (S.Context)
7417       RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
7418 
7419   D->addAttr(RCA);
7420 }
7421 
7422 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7423   if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
7424     if (NSD->isAnonymousNamespace()) {
7425       S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
7426       // Do not want to attach the attribute to the namespace because that will
7427       // cause confusing diagnostic reports for uses of declarations within the
7428       // namespace.
7429       return;
7430     }
7431   } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl,
7432                  UnresolvedUsingValueDecl>(D)) {
7433     S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
7434         << AL;
7435     return;
7436   }
7437 
7438   // Handle the cases where the attribute has a text message.
7439   StringRef Str, Replacement;
7440   if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
7441       !S.checkStringLiteralArgumentAttr(AL, 0, Str))
7442     return;
7443 
7444   // Support a single optional message only for Declspec and [[]] spellings.
7445   if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax())
7446     AL.checkAtMostNumArgs(S, 1);
7447   else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
7448            !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
7449     return;
7450 
7451   if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
7452     S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
7453 
7454   D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
7455 }
7456 
7457 static bool isGlobalVar(const Decl *D) {
7458   if (const auto *S = dyn_cast<VarDecl>(D))
7459     return S->hasGlobalStorage();
7460   return false;
7461 }
7462 
7463 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7464   if (!AL.checkAtLeastNumArgs(S, 1))
7465     return;
7466 
7467   std::vector<StringRef> Sanitizers;
7468 
7469   for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
7470     StringRef SanitizerName;
7471     SourceLocation LiteralLoc;
7472 
7473     if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
7474       return;
7475 
7476     if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
7477             SanitizerMask() &&
7478         SanitizerName != "coverage")
7479       S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
7480     else if (isGlobalVar(D) && SanitizerName != "address")
7481       S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7482           << AL << ExpectedFunctionOrMethod;
7483     Sanitizers.push_back(SanitizerName);
7484   }
7485 
7486   D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
7487                                               Sanitizers.size()));
7488 }
7489 
7490 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
7491                                          const ParsedAttr &AL) {
7492   StringRef AttrName = AL.getAttrName()->getName();
7493   normalizeName(AttrName);
7494   StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
7495                                 .Case("no_address_safety_analysis", "address")
7496                                 .Case("no_sanitize_address", "address")
7497                                 .Case("no_sanitize_thread", "thread")
7498                                 .Case("no_sanitize_memory", "memory");
7499   if (isGlobalVar(D) && SanitizerName != "address")
7500     S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7501         << AL << ExpectedFunction;
7502 
7503   // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
7504   // NoSanitizeAttr object; but we need to calculate the correct spelling list
7505   // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
7506   // has the same spellings as the index for NoSanitizeAttr. We don't have a
7507   // general way to "translate" between the two, so this hack attempts to work
7508   // around the issue with hard-coded indices. This is critical for calling
7509   // getSpelling() or prettyPrint() on the resulting semantic attribute object
7510   // without failing assertions.
7511   unsigned TranslatedSpellingIndex = 0;
7512   if (AL.isStandardAttributeSyntax())
7513     TranslatedSpellingIndex = 1;
7514 
7515   AttributeCommonInfo Info = AL;
7516   Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
7517   D->addAttr(::new (S.Context)
7518                  NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
7519 }
7520 
7521 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7522   if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
7523     D->addAttr(Internal);
7524 }
7525 
7526 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7527   if (S.LangOpts.getOpenCLCompatibleVersion() < 200)
7528     S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
7529         << AL << "2.0" << 1;
7530   else
7531     S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
7532         << AL << S.LangOpts.getOpenCLVersionString();
7533 }
7534 
7535 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7536   if (D->isInvalidDecl())
7537     return;
7538 
7539   // Check if there is only one access qualifier.
7540   if (D->hasAttr<OpenCLAccessAttr>()) {
7541     if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
7542         AL.getSemanticSpelling()) {
7543       S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
7544           << AL.getAttrName()->getName() << AL.getRange();
7545     } else {
7546       S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
7547           << D->getSourceRange();
7548       D->setInvalidDecl(true);
7549       return;
7550     }
7551   }
7552 
7553   // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that
7554   // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel
7555   // cannot read from and write to the same pipe object. Using the read_write
7556   // (or __read_write) qualifier with the pipe qualifier is a compilation error.
7557   // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the
7558   // __opencl_c_read_write_images feature, image objects specified as arguments
7559   // to a kernel can additionally be declared to be read-write.
7560   // C++ for OpenCL 1.0 inherits rule from OpenCL C v2.0.
7561   // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0.
7562   if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
7563     const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
7564     if (AL.getAttrName()->getName().find("read_write") != StringRef::npos) {
7565       bool ReadWriteImagesUnsupported =
7566           (S.getLangOpts().getOpenCLCompatibleVersion() < 200) ||
7567           (S.getLangOpts().getOpenCLCompatibleVersion() == 300 &&
7568            !S.getOpenCLOptions().isSupported("__opencl_c_read_write_images",
7569                                              S.getLangOpts()));
7570       if (ReadWriteImagesUnsupported || DeclTy->isPipeType()) {
7571         S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
7572             << AL << PDecl->getType() << DeclTy->isImageType();
7573         D->setInvalidDecl(true);
7574         return;
7575       }
7576     }
7577   }
7578 
7579   D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
7580 }
7581 
7582 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7583   // The 'sycl_kernel' attribute applies only to function templates.
7584   const auto *FD = cast<FunctionDecl>(D);
7585   const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
7586   assert(FT && "Function template is expected");
7587 
7588   // Function template must have at least two template parameters.
7589   const TemplateParameterList *TL = FT->getTemplateParameters();
7590   if (TL->size() < 2) {
7591     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
7592     return;
7593   }
7594 
7595   // Template parameters must be typenames.
7596   for (unsigned I = 0; I < 2; ++I) {
7597     const NamedDecl *TParam = TL->getParam(I);
7598     if (isa<NonTypeTemplateParmDecl>(TParam)) {
7599       S.Diag(FT->getLocation(),
7600              diag::warn_sycl_kernel_invalid_template_param_type);
7601       return;
7602     }
7603   }
7604 
7605   // Function must have at least one argument.
7606   if (getFunctionOrMethodNumParams(D) != 1) {
7607     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
7608     return;
7609   }
7610 
7611   // Function must return void.
7612   QualType RetTy = getFunctionOrMethodResultType(D);
7613   if (!RetTy->isVoidType()) {
7614     S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
7615     return;
7616   }
7617 
7618   handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
7619 }
7620 
7621 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
7622   if (!cast<VarDecl>(D)->hasGlobalStorage()) {
7623     S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
7624         << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
7625     return;
7626   }
7627 
7628   if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
7629     handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A);
7630   else
7631     handleSimpleAttribute<NoDestroyAttr>(S, D, A);
7632 }
7633 
7634 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7635   assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
7636          "uninitialized is only valid on automatic duration variables");
7637   D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
7638 }
7639 
7640 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
7641                                         bool DiagnoseFailure) {
7642   QualType Ty = VD->getType();
7643   if (!Ty->isObjCRetainableType()) {
7644     if (DiagnoseFailure) {
7645       S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
7646           << 0;
7647     }
7648     return false;
7649   }
7650 
7651   Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
7652 
7653   // Sema::inferObjCARCLifetime must run after processing decl attributes
7654   // (because __block lowers to an attribute), so if the lifetime hasn't been
7655   // explicitly specified, infer it locally now.
7656   if (LifetimeQual == Qualifiers::OCL_None)
7657     LifetimeQual = Ty->getObjCARCImplicitLifetime();
7658 
7659   // The attributes only really makes sense for __strong variables; ignore any
7660   // attempts to annotate a parameter with any other lifetime qualifier.
7661   if (LifetimeQual != Qualifiers::OCL_Strong) {
7662     if (DiagnoseFailure) {
7663       S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
7664           << 1;
7665     }
7666     return false;
7667   }
7668 
7669   // Tampering with the type of a VarDecl here is a bit of a hack, but we need
7670   // to ensure that the variable is 'const' so that we can error on
7671   // modification, which can otherwise over-release.
7672   VD->setType(Ty.withConst());
7673   VD->setARCPseudoStrong(true);
7674   return true;
7675 }
7676 
7677 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
7678                                              const ParsedAttr &AL) {
7679   if (auto *VD = dyn_cast<VarDecl>(D)) {
7680     assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
7681     if (!VD->hasLocalStorage()) {
7682       S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
7683           << 0;
7684       return;
7685     }
7686 
7687     if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
7688       return;
7689 
7690     handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
7691     return;
7692   }
7693 
7694   // If D is a function-like declaration (method, block, or function), then we
7695   // make every parameter psuedo-strong.
7696   unsigned NumParams =
7697       hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
7698   for (unsigned I = 0; I != NumParams; ++I) {
7699     auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
7700     QualType Ty = PVD->getType();
7701 
7702     // If a user wrote a parameter with __strong explicitly, then assume they
7703     // want "real" strong semantics for that parameter. This works because if
7704     // the parameter was written with __strong, then the strong qualifier will
7705     // be non-local.
7706     if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
7707         Qualifiers::OCL_Strong)
7708       continue;
7709 
7710     tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
7711   }
7712   handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
7713 }
7714 
7715 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7716   // Check that the return type is a `typedef int kern_return_t` or a typedef
7717   // around it, because otherwise MIG convention checks make no sense.
7718   // BlockDecl doesn't store a return type, so it's annoying to check,
7719   // so let's skip it for now.
7720   if (!isa<BlockDecl>(D)) {
7721     QualType T = getFunctionOrMethodResultType(D);
7722     bool IsKernReturnT = false;
7723     while (const auto *TT = T->getAs<TypedefType>()) {
7724       IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
7725       T = TT->desugar();
7726     }
7727     if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
7728       S.Diag(D->getBeginLoc(),
7729              diag::warn_mig_server_routine_does_not_return_kern_return_t);
7730       return;
7731     }
7732   }
7733 
7734   handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
7735 }
7736 
7737 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7738   // Warn if the return type is not a pointer or reference type.
7739   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7740     QualType RetTy = FD->getReturnType();
7741     if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
7742       S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
7743           << AL.getRange() << RetTy;
7744       return;
7745     }
7746   }
7747 
7748   handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
7749 }
7750 
7751 static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7752   if (AL.isUsedAsTypeAttr())
7753     return;
7754   // Warn if the parameter is definitely not an output parameter.
7755   if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
7756     if (PVD->getType()->isIntegerType()) {
7757       S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
7758           << AL.getRange();
7759       return;
7760     }
7761   }
7762   StringRef Argument;
7763   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
7764     return;
7765   D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
7766 }
7767 
7768 template<typename Attr>
7769 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7770   StringRef Argument;
7771   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
7772     return;
7773   D->addAttr(Attr::Create(S.Context, Argument, AL));
7774 }
7775 
7776 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7777   // The guard attribute takes a single identifier argument.
7778 
7779   if (!AL.isArgIdent(0)) {
7780     S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7781         << AL << AANT_ArgumentIdentifier;
7782     return;
7783   }
7784 
7785   CFGuardAttr::GuardArg Arg;
7786   IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
7787   if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
7788     S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
7789     return;
7790   }
7791 
7792   D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
7793 }
7794 
7795 
7796 template <typename AttrTy>
7797 static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) {
7798   auto Attrs = D->specific_attrs<AttrTy>();
7799   auto I = llvm::find_if(Attrs,
7800                          [Name](const AttrTy *A) {
7801                            return A->getTCBName() == Name;
7802                          });
7803   return I == Attrs.end() ? nullptr : *I;
7804 }
7805 
7806 template <typename AttrTy, typename ConflictingAttrTy>
7807 static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7808   StringRef Argument;
7809   if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
7810     return;
7811 
7812   // A function cannot be have both regular and leaf membership in the same TCB.
7813   if (const ConflictingAttrTy *ConflictingAttr =
7814       findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) {
7815     // We could attach a note to the other attribute but in this case
7816     // there's no need given how the two are very close to each other.
7817     S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes)
7818       << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName()
7819       << Argument;
7820 
7821     // Error recovery: drop the non-leaf attribute so that to suppress
7822     // all future warnings caused by erroneous attributes. The leaf attribute
7823     // needs to be kept because it can only suppresses warnings, not cause them.
7824     D->dropAttr<EnforceTCBAttr>();
7825     return;
7826   }
7827 
7828   D->addAttr(AttrTy::Create(S.Context, Argument, AL));
7829 }
7830 
7831 template <typename AttrTy, typename ConflictingAttrTy>
7832 static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) {
7833   // Check if the new redeclaration has different leaf-ness in the same TCB.
7834   StringRef TCBName = AL.getTCBName();
7835   if (const ConflictingAttrTy *ConflictingAttr =
7836       findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) {
7837     S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes)
7838       << ConflictingAttr->getAttrName()->getName()
7839       << AL.getAttrName()->getName() << TCBName;
7840 
7841     // Add a note so that the user could easily find the conflicting attribute.
7842     S.Diag(AL.getLoc(), diag::note_conflicting_attribute);
7843 
7844     // More error recovery.
7845     D->dropAttr<EnforceTCBAttr>();
7846     return nullptr;
7847   }
7848 
7849   ASTContext &Context = S.getASTContext();
7850   return ::new(Context) AttrTy(Context, AL, AL.getTCBName());
7851 }
7852 
7853 EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) {
7854   return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>(
7855       *this, D, AL);
7856 }
7857 
7858 EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr(
7859     Decl *D, const EnforceTCBLeafAttr &AL) {
7860   return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>(
7861       *this, D, AL);
7862 }
7863 
7864 //===----------------------------------------------------------------------===//
7865 // Top Level Sema Entry Points
7866 //===----------------------------------------------------------------------===//
7867 
7868 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
7869 /// the attribute applies to decls.  If the attribute is a type attribute, just
7870 /// silently ignore it if a GNU attribute.
7871 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
7872                                  const ParsedAttr &AL,
7873                                  bool IncludeCXX11Attributes) {
7874   if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
7875     return;
7876 
7877   // Ignore C++11 attributes on declarator chunks: they appertain to the type
7878   // instead.
7879   if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
7880     return;
7881 
7882   // Unknown attributes are automatically warned on. Target-specific attributes
7883   // which do not apply to the current target architecture are treated as
7884   // though they were unknown attributes.
7885   if (AL.getKind() == ParsedAttr::UnknownAttribute ||
7886       !AL.existsInTarget(S.Context.getTargetInfo())) {
7887     S.Diag(AL.getLoc(),
7888            AL.isDeclspecAttribute()
7889                ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
7890                : (unsigned)diag::warn_unknown_attribute_ignored)
7891         << AL << AL.getRange();
7892     return;
7893   }
7894 
7895   if (S.checkCommonAttributeFeatures(D, AL))
7896     return;
7897 
7898   switch (AL.getKind()) {
7899   default:
7900     if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled)
7901       break;
7902     if (!AL.isStmtAttr()) {
7903       // Type attributes are handled elsewhere; silently move on.
7904       assert(AL.isTypeAttr() && "Non-type attribute not handled");
7905       break;
7906     }
7907     // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
7908     // statement attribute is not written on a declaration, but this code is
7909     // needed for attributes in Attr.td that do not list any subjects.
7910     S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
7911         << AL << D->getLocation();
7912     break;
7913   case ParsedAttr::AT_Interrupt:
7914     handleInterruptAttr(S, D, AL);
7915     break;
7916   case ParsedAttr::AT_X86ForceAlignArgPointer:
7917     handleX86ForceAlignArgPointerAttr(S, D, AL);
7918     break;
7919   case ParsedAttr::AT_DLLExport:
7920   case ParsedAttr::AT_DLLImport:
7921     handleDLLAttr(S, D, AL);
7922     break;
7923   case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
7924     handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
7925     break;
7926   case ParsedAttr::AT_AMDGPUWavesPerEU:
7927     handleAMDGPUWavesPerEUAttr(S, D, AL);
7928     break;
7929   case ParsedAttr::AT_AMDGPUNumSGPR:
7930     handleAMDGPUNumSGPRAttr(S, D, AL);
7931     break;
7932   case ParsedAttr::AT_AMDGPUNumVGPR:
7933     handleAMDGPUNumVGPRAttr(S, D, AL);
7934     break;
7935   case ParsedAttr::AT_AVRSignal:
7936     handleAVRSignalAttr(S, D, AL);
7937     break;
7938   case ParsedAttr::AT_BPFPreserveAccessIndex:
7939     handleBPFPreserveAccessIndexAttr(S, D, AL);
7940     break;
7941   case ParsedAttr::AT_BTFTag:
7942     handleBTFTagAttr(S, D, AL);
7943     break;
7944   case ParsedAttr::AT_WebAssemblyExportName:
7945     handleWebAssemblyExportNameAttr(S, D, AL);
7946     break;
7947   case ParsedAttr::AT_WebAssemblyImportModule:
7948     handleWebAssemblyImportModuleAttr(S, D, AL);
7949     break;
7950   case ParsedAttr::AT_WebAssemblyImportName:
7951     handleWebAssemblyImportNameAttr(S, D, AL);
7952     break;
7953   case ParsedAttr::AT_IBOutlet:
7954     handleIBOutlet(S, D, AL);
7955     break;
7956   case ParsedAttr::AT_IBOutletCollection:
7957     handleIBOutletCollection(S, D, AL);
7958     break;
7959   case ParsedAttr::AT_IFunc:
7960     handleIFuncAttr(S, D, AL);
7961     break;
7962   case ParsedAttr::AT_Alias:
7963     handleAliasAttr(S, D, AL);
7964     break;
7965   case ParsedAttr::AT_Aligned:
7966     handleAlignedAttr(S, D, AL);
7967     break;
7968   case ParsedAttr::AT_AlignValue:
7969     handleAlignValueAttr(S, D, AL);
7970     break;
7971   case ParsedAttr::AT_AllocSize:
7972     handleAllocSizeAttr(S, D, AL);
7973     break;
7974   case ParsedAttr::AT_AlwaysInline:
7975     handleAlwaysInlineAttr(S, D, AL);
7976     break;
7977   case ParsedAttr::AT_AnalyzerNoReturn:
7978     handleAnalyzerNoReturnAttr(S, D, AL);
7979     break;
7980   case ParsedAttr::AT_TLSModel:
7981     handleTLSModelAttr(S, D, AL);
7982     break;
7983   case ParsedAttr::AT_Annotate:
7984     handleAnnotateAttr(S, D, AL);
7985     break;
7986   case ParsedAttr::AT_Availability:
7987     handleAvailabilityAttr(S, D, AL);
7988     break;
7989   case ParsedAttr::AT_CarriesDependency:
7990     handleDependencyAttr(S, scope, D, AL);
7991     break;
7992   case ParsedAttr::AT_CPUDispatch:
7993   case ParsedAttr::AT_CPUSpecific:
7994     handleCPUSpecificAttr(S, D, AL);
7995     break;
7996   case ParsedAttr::AT_Common:
7997     handleCommonAttr(S, D, AL);
7998     break;
7999   case ParsedAttr::AT_CUDAConstant:
8000     handleConstantAttr(S, D, AL);
8001     break;
8002   case ParsedAttr::AT_PassObjectSize:
8003     handlePassObjectSizeAttr(S, D, AL);
8004     break;
8005   case ParsedAttr::AT_Constructor:
8006       handleConstructorAttr(S, D, AL);
8007     break;
8008   case ParsedAttr::AT_Deprecated:
8009     handleDeprecatedAttr(S, D, AL);
8010     break;
8011   case ParsedAttr::AT_Destructor:
8012       handleDestructorAttr(S, D, AL);
8013     break;
8014   case ParsedAttr::AT_EnableIf:
8015     handleEnableIfAttr(S, D, AL);
8016     break;
8017   case ParsedAttr::AT_Error:
8018     handleErrorAttr(S, D, AL);
8019     break;
8020   case ParsedAttr::AT_DiagnoseIf:
8021     handleDiagnoseIfAttr(S, D, AL);
8022     break;
8023   case ParsedAttr::AT_NoBuiltin:
8024     handleNoBuiltinAttr(S, D, AL);
8025     break;
8026   case ParsedAttr::AT_ExtVectorType:
8027     handleExtVectorTypeAttr(S, D, AL);
8028     break;
8029   case ParsedAttr::AT_ExternalSourceSymbol:
8030     handleExternalSourceSymbolAttr(S, D, AL);
8031     break;
8032   case ParsedAttr::AT_MinSize:
8033     handleMinSizeAttr(S, D, AL);
8034     break;
8035   case ParsedAttr::AT_OptimizeNone:
8036     handleOptimizeNoneAttr(S, D, AL);
8037     break;
8038   case ParsedAttr::AT_EnumExtensibility:
8039     handleEnumExtensibilityAttr(S, D, AL);
8040     break;
8041   case ParsedAttr::AT_SYCLKernel:
8042     handleSYCLKernelAttr(S, D, AL);
8043     break;
8044   case ParsedAttr::AT_Format:
8045     handleFormatAttr(S, D, AL);
8046     break;
8047   case ParsedAttr::AT_FormatArg:
8048     handleFormatArgAttr(S, D, AL);
8049     break;
8050   case ParsedAttr::AT_Callback:
8051     handleCallbackAttr(S, D, AL);
8052     break;
8053   case ParsedAttr::AT_CalledOnce:
8054     handleCalledOnceAttr(S, D, AL);
8055     break;
8056   case ParsedAttr::AT_CUDAGlobal:
8057     handleGlobalAttr(S, D, AL);
8058     break;
8059   case ParsedAttr::AT_CUDADevice:
8060     handleDeviceAttr(S, D, AL);
8061     break;
8062   case ParsedAttr::AT_HIPManaged:
8063     handleManagedAttr(S, D, AL);
8064     break;
8065   case ParsedAttr::AT_GNUInline:
8066     handleGNUInlineAttr(S, D, AL);
8067     break;
8068   case ParsedAttr::AT_CUDALaunchBounds:
8069     handleLaunchBoundsAttr(S, D, AL);
8070     break;
8071   case ParsedAttr::AT_Restrict:
8072     handleRestrictAttr(S, D, AL);
8073     break;
8074   case ParsedAttr::AT_Mode:
8075     handleModeAttr(S, D, AL);
8076     break;
8077   case ParsedAttr::AT_NonNull:
8078     if (auto *PVD = dyn_cast<ParmVarDecl>(D))
8079       handleNonNullAttrParameter(S, PVD, AL);
8080     else
8081       handleNonNullAttr(S, D, AL);
8082     break;
8083   case ParsedAttr::AT_ReturnsNonNull:
8084     handleReturnsNonNullAttr(S, D, AL);
8085     break;
8086   case ParsedAttr::AT_NoEscape:
8087     handleNoEscapeAttr(S, D, AL);
8088     break;
8089   case ParsedAttr::AT_AssumeAligned:
8090     handleAssumeAlignedAttr(S, D, AL);
8091     break;
8092   case ParsedAttr::AT_AllocAlign:
8093     handleAllocAlignAttr(S, D, AL);
8094     break;
8095   case ParsedAttr::AT_Ownership:
8096     handleOwnershipAttr(S, D, AL);
8097     break;
8098   case ParsedAttr::AT_Naked:
8099     handleNakedAttr(S, D, AL);
8100     break;
8101   case ParsedAttr::AT_NoReturn:
8102     handleNoReturnAttr(S, D, AL);
8103     break;
8104   case ParsedAttr::AT_AnyX86NoCfCheck:
8105     handleNoCfCheckAttr(S, D, AL);
8106     break;
8107   case ParsedAttr::AT_NoThrow:
8108     if (!AL.isUsedAsTypeAttr())
8109       handleSimpleAttribute<NoThrowAttr>(S, D, AL);
8110     break;
8111   case ParsedAttr::AT_CUDAShared:
8112     handleSharedAttr(S, D, AL);
8113     break;
8114   case ParsedAttr::AT_VecReturn:
8115     handleVecReturnAttr(S, D, AL);
8116     break;
8117   case ParsedAttr::AT_ObjCOwnership:
8118     handleObjCOwnershipAttr(S, D, AL);
8119     break;
8120   case ParsedAttr::AT_ObjCPreciseLifetime:
8121     handleObjCPreciseLifetimeAttr(S, D, AL);
8122     break;
8123   case ParsedAttr::AT_ObjCReturnsInnerPointer:
8124     handleObjCReturnsInnerPointerAttr(S, D, AL);
8125     break;
8126   case ParsedAttr::AT_ObjCRequiresSuper:
8127     handleObjCRequiresSuperAttr(S, D, AL);
8128     break;
8129   case ParsedAttr::AT_ObjCBridge:
8130     handleObjCBridgeAttr(S, D, AL);
8131     break;
8132   case ParsedAttr::AT_ObjCBridgeMutable:
8133     handleObjCBridgeMutableAttr(S, D, AL);
8134     break;
8135   case ParsedAttr::AT_ObjCBridgeRelated:
8136     handleObjCBridgeRelatedAttr(S, D, AL);
8137     break;
8138   case ParsedAttr::AT_ObjCDesignatedInitializer:
8139     handleObjCDesignatedInitializer(S, D, AL);
8140     break;
8141   case ParsedAttr::AT_ObjCRuntimeName:
8142     handleObjCRuntimeName(S, D, AL);
8143     break;
8144   case ParsedAttr::AT_ObjCBoxable:
8145     handleObjCBoxable(S, D, AL);
8146     break;
8147   case ParsedAttr::AT_NSErrorDomain:
8148     handleNSErrorDomain(S, D, AL);
8149     break;
8150   case ParsedAttr::AT_CFConsumed:
8151   case ParsedAttr::AT_NSConsumed:
8152   case ParsedAttr::AT_OSConsumed:
8153     S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
8154                        /*IsTemplateInstantiation=*/false);
8155     break;
8156   case ParsedAttr::AT_OSReturnsRetainedOnZero:
8157     handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
8158         S, D, AL, isValidOSObjectOutParameter(D),
8159         diag::warn_ns_attribute_wrong_parameter_type,
8160         /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
8161     break;
8162   case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
8163     handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
8164         S, D, AL, isValidOSObjectOutParameter(D),
8165         diag::warn_ns_attribute_wrong_parameter_type,
8166         /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
8167     break;
8168   case ParsedAttr::AT_NSReturnsAutoreleased:
8169   case ParsedAttr::AT_NSReturnsNotRetained:
8170   case ParsedAttr::AT_NSReturnsRetained:
8171   case ParsedAttr::AT_CFReturnsNotRetained:
8172   case ParsedAttr::AT_CFReturnsRetained:
8173   case ParsedAttr::AT_OSReturnsNotRetained:
8174   case ParsedAttr::AT_OSReturnsRetained:
8175     handleXReturnsXRetainedAttr(S, D, AL);
8176     break;
8177   case ParsedAttr::AT_WorkGroupSizeHint:
8178     handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
8179     break;
8180   case ParsedAttr::AT_ReqdWorkGroupSize:
8181     handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
8182     break;
8183   case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
8184     handleSubGroupSize(S, D, AL);
8185     break;
8186   case ParsedAttr::AT_VecTypeHint:
8187     handleVecTypeHint(S, D, AL);
8188     break;
8189   case ParsedAttr::AT_InitPriority:
8190       handleInitPriorityAttr(S, D, AL);
8191     break;
8192   case ParsedAttr::AT_Packed:
8193     handlePackedAttr(S, D, AL);
8194     break;
8195   case ParsedAttr::AT_PreferredName:
8196     handlePreferredName(S, D, AL);
8197     break;
8198   case ParsedAttr::AT_Section:
8199     handleSectionAttr(S, D, AL);
8200     break;
8201   case ParsedAttr::AT_CodeSeg:
8202     handleCodeSegAttr(S, D, AL);
8203     break;
8204   case ParsedAttr::AT_Target:
8205     handleTargetAttr(S, D, AL);
8206     break;
8207   case ParsedAttr::AT_MinVectorWidth:
8208     handleMinVectorWidthAttr(S, D, AL);
8209     break;
8210   case ParsedAttr::AT_Unavailable:
8211     handleAttrWithMessage<UnavailableAttr>(S, D, AL);
8212     break;
8213   case ParsedAttr::AT_Assumption:
8214     handleAssumumptionAttr(S, D, AL);
8215     break;
8216   case ParsedAttr::AT_ObjCDirect:
8217     handleObjCDirectAttr(S, D, AL);
8218     break;
8219   case ParsedAttr::AT_ObjCDirectMembers:
8220     handleObjCDirectMembersAttr(S, D, AL);
8221     handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
8222     break;
8223   case ParsedAttr::AT_ObjCExplicitProtocolImpl:
8224     handleObjCSuppresProtocolAttr(S, D, AL);
8225     break;
8226   case ParsedAttr::AT_Unused:
8227     handleUnusedAttr(S, D, AL);
8228     break;
8229   case ParsedAttr::AT_Visibility:
8230     handleVisibilityAttr(S, D, AL, false);
8231     break;
8232   case ParsedAttr::AT_TypeVisibility:
8233     handleVisibilityAttr(S, D, AL, true);
8234     break;
8235   case ParsedAttr::AT_WarnUnusedResult:
8236     handleWarnUnusedResult(S, D, AL);
8237     break;
8238   case ParsedAttr::AT_WeakRef:
8239     handleWeakRefAttr(S, D, AL);
8240     break;
8241   case ParsedAttr::AT_WeakImport:
8242     handleWeakImportAttr(S, D, AL);
8243     break;
8244   case ParsedAttr::AT_TransparentUnion:
8245     handleTransparentUnionAttr(S, D, AL);
8246     break;
8247   case ParsedAttr::AT_ObjCMethodFamily:
8248     handleObjCMethodFamilyAttr(S, D, AL);
8249     break;
8250   case ParsedAttr::AT_ObjCNSObject:
8251     handleObjCNSObject(S, D, AL);
8252     break;
8253   case ParsedAttr::AT_ObjCIndependentClass:
8254     handleObjCIndependentClass(S, D, AL);
8255     break;
8256   case ParsedAttr::AT_Blocks:
8257     handleBlocksAttr(S, D, AL);
8258     break;
8259   case ParsedAttr::AT_Sentinel:
8260     handleSentinelAttr(S, D, AL);
8261     break;
8262   case ParsedAttr::AT_Cleanup:
8263     handleCleanupAttr(S, D, AL);
8264     break;
8265   case ParsedAttr::AT_NoDebug:
8266     handleNoDebugAttr(S, D, AL);
8267     break;
8268   case ParsedAttr::AT_CmseNSEntry:
8269     handleCmseNSEntryAttr(S, D, AL);
8270     break;
8271   case ParsedAttr::AT_StdCall:
8272   case ParsedAttr::AT_CDecl:
8273   case ParsedAttr::AT_FastCall:
8274   case ParsedAttr::AT_ThisCall:
8275   case ParsedAttr::AT_Pascal:
8276   case ParsedAttr::AT_RegCall:
8277   case ParsedAttr::AT_SwiftCall:
8278   case ParsedAttr::AT_SwiftAsyncCall:
8279   case ParsedAttr::AT_VectorCall:
8280   case ParsedAttr::AT_MSABI:
8281   case ParsedAttr::AT_SysVABI:
8282   case ParsedAttr::AT_Pcs:
8283   case ParsedAttr::AT_IntelOclBicc:
8284   case ParsedAttr::AT_PreserveMost:
8285   case ParsedAttr::AT_PreserveAll:
8286   case ParsedAttr::AT_AArch64VectorPcs:
8287     handleCallConvAttr(S, D, AL);
8288     break;
8289   case ParsedAttr::AT_Suppress:
8290     handleSuppressAttr(S, D, AL);
8291     break;
8292   case ParsedAttr::AT_Owner:
8293   case ParsedAttr::AT_Pointer:
8294     handleLifetimeCategoryAttr(S, D, AL);
8295     break;
8296   case ParsedAttr::AT_OpenCLAccess:
8297     handleOpenCLAccessAttr(S, D, AL);
8298     break;
8299   case ParsedAttr::AT_OpenCLNoSVM:
8300     handleOpenCLNoSVMAttr(S, D, AL);
8301     break;
8302   case ParsedAttr::AT_SwiftContext:
8303     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext);
8304     break;
8305   case ParsedAttr::AT_SwiftAsyncContext:
8306     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftAsyncContext);
8307     break;
8308   case ParsedAttr::AT_SwiftErrorResult:
8309     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult);
8310     break;
8311   case ParsedAttr::AT_SwiftIndirectResult:
8312     S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult);
8313     break;
8314   case ParsedAttr::AT_InternalLinkage:
8315     handleInternalLinkageAttr(S, D, AL);
8316     break;
8317 
8318   // Microsoft attributes:
8319   case ParsedAttr::AT_LayoutVersion:
8320     handleLayoutVersion(S, D, AL);
8321     break;
8322   case ParsedAttr::AT_Uuid:
8323     handleUuidAttr(S, D, AL);
8324     break;
8325   case ParsedAttr::AT_MSInheritance:
8326     handleMSInheritanceAttr(S, D, AL);
8327     break;
8328   case ParsedAttr::AT_Thread:
8329     handleDeclspecThreadAttr(S, D, AL);
8330     break;
8331 
8332   case ParsedAttr::AT_AbiTag:
8333     handleAbiTagAttr(S, D, AL);
8334     break;
8335   case ParsedAttr::AT_CFGuard:
8336     handleCFGuardAttr(S, D, AL);
8337     break;
8338 
8339   // Thread safety attributes:
8340   case ParsedAttr::AT_AssertExclusiveLock:
8341     handleAssertExclusiveLockAttr(S, D, AL);
8342     break;
8343   case ParsedAttr::AT_AssertSharedLock:
8344     handleAssertSharedLockAttr(S, D, AL);
8345     break;
8346   case ParsedAttr::AT_PtGuardedVar:
8347     handlePtGuardedVarAttr(S, D, AL);
8348     break;
8349   case ParsedAttr::AT_NoSanitize:
8350     handleNoSanitizeAttr(S, D, AL);
8351     break;
8352   case ParsedAttr::AT_NoSanitizeSpecific:
8353     handleNoSanitizeSpecificAttr(S, D, AL);
8354     break;
8355   case ParsedAttr::AT_GuardedBy:
8356     handleGuardedByAttr(S, D, AL);
8357     break;
8358   case ParsedAttr::AT_PtGuardedBy:
8359     handlePtGuardedByAttr(S, D, AL);
8360     break;
8361   case ParsedAttr::AT_ExclusiveTrylockFunction:
8362     handleExclusiveTrylockFunctionAttr(S, D, AL);
8363     break;
8364   case ParsedAttr::AT_LockReturned:
8365     handleLockReturnedAttr(S, D, AL);
8366     break;
8367   case ParsedAttr::AT_LocksExcluded:
8368     handleLocksExcludedAttr(S, D, AL);
8369     break;
8370   case ParsedAttr::AT_SharedTrylockFunction:
8371     handleSharedTrylockFunctionAttr(S, D, AL);
8372     break;
8373   case ParsedAttr::AT_AcquiredBefore:
8374     handleAcquiredBeforeAttr(S, D, AL);
8375     break;
8376   case ParsedAttr::AT_AcquiredAfter:
8377     handleAcquiredAfterAttr(S, D, AL);
8378     break;
8379 
8380   // Capability analysis attributes.
8381   case ParsedAttr::AT_Capability:
8382   case ParsedAttr::AT_Lockable:
8383     handleCapabilityAttr(S, D, AL);
8384     break;
8385   case ParsedAttr::AT_RequiresCapability:
8386     handleRequiresCapabilityAttr(S, D, AL);
8387     break;
8388 
8389   case ParsedAttr::AT_AssertCapability:
8390     handleAssertCapabilityAttr(S, D, AL);
8391     break;
8392   case ParsedAttr::AT_AcquireCapability:
8393     handleAcquireCapabilityAttr(S, D, AL);
8394     break;
8395   case ParsedAttr::AT_ReleaseCapability:
8396     handleReleaseCapabilityAttr(S, D, AL);
8397     break;
8398   case ParsedAttr::AT_TryAcquireCapability:
8399     handleTryAcquireCapabilityAttr(S, D, AL);
8400     break;
8401 
8402   // Consumed analysis attributes.
8403   case ParsedAttr::AT_Consumable:
8404     handleConsumableAttr(S, D, AL);
8405     break;
8406   case ParsedAttr::AT_CallableWhen:
8407     handleCallableWhenAttr(S, D, AL);
8408     break;
8409   case ParsedAttr::AT_ParamTypestate:
8410     handleParamTypestateAttr(S, D, AL);
8411     break;
8412   case ParsedAttr::AT_ReturnTypestate:
8413     handleReturnTypestateAttr(S, D, AL);
8414     break;
8415   case ParsedAttr::AT_SetTypestate:
8416     handleSetTypestateAttr(S, D, AL);
8417     break;
8418   case ParsedAttr::AT_TestTypestate:
8419     handleTestTypestateAttr(S, D, AL);
8420     break;
8421 
8422   // Type safety attributes.
8423   case ParsedAttr::AT_ArgumentWithTypeTag:
8424     handleArgumentWithTypeTagAttr(S, D, AL);
8425     break;
8426   case ParsedAttr::AT_TypeTagForDatatype:
8427     handleTypeTagForDatatypeAttr(S, D, AL);
8428     break;
8429 
8430   // Swift attributes.
8431   case ParsedAttr::AT_SwiftAsyncName:
8432     handleSwiftAsyncName(S, D, AL);
8433     break;
8434   case ParsedAttr::AT_SwiftAttr:
8435     handleSwiftAttrAttr(S, D, AL);
8436     break;
8437   case ParsedAttr::AT_SwiftBridge:
8438     handleSwiftBridge(S, D, AL);
8439     break;
8440   case ParsedAttr::AT_SwiftError:
8441     handleSwiftError(S, D, AL);
8442     break;
8443   case ParsedAttr::AT_SwiftName:
8444     handleSwiftName(S, D, AL);
8445     break;
8446   case ParsedAttr::AT_SwiftNewType:
8447     handleSwiftNewType(S, D, AL);
8448     break;
8449   case ParsedAttr::AT_SwiftAsync:
8450     handleSwiftAsyncAttr(S, D, AL);
8451     break;
8452   case ParsedAttr::AT_SwiftAsyncError:
8453     handleSwiftAsyncError(S, D, AL);
8454     break;
8455 
8456   // XRay attributes.
8457   case ParsedAttr::AT_XRayLogArgs:
8458     handleXRayLogArgsAttr(S, D, AL);
8459     break;
8460 
8461   case ParsedAttr::AT_PatchableFunctionEntry:
8462     handlePatchableFunctionEntryAttr(S, D, AL);
8463     break;
8464 
8465   case ParsedAttr::AT_AlwaysDestroy:
8466   case ParsedAttr::AT_NoDestroy:
8467     handleDestroyAttr(S, D, AL);
8468     break;
8469 
8470   case ParsedAttr::AT_Uninitialized:
8471     handleUninitializedAttr(S, D, AL);
8472     break;
8473 
8474   case ParsedAttr::AT_ObjCExternallyRetained:
8475     handleObjCExternallyRetainedAttr(S, D, AL);
8476     break;
8477 
8478   case ParsedAttr::AT_MIGServerRoutine:
8479     handleMIGServerRoutineAttr(S, D, AL);
8480     break;
8481 
8482   case ParsedAttr::AT_MSAllocator:
8483     handleMSAllocatorAttr(S, D, AL);
8484     break;
8485 
8486   case ParsedAttr::AT_ArmBuiltinAlias:
8487     handleArmBuiltinAliasAttr(S, D, AL);
8488     break;
8489 
8490   case ParsedAttr::AT_AcquireHandle:
8491     handleAcquireHandleAttr(S, D, AL);
8492     break;
8493 
8494   case ParsedAttr::AT_ReleaseHandle:
8495     handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
8496     break;
8497 
8498   case ParsedAttr::AT_UseHandle:
8499     handleHandleAttr<UseHandleAttr>(S, D, AL);
8500     break;
8501 
8502   case ParsedAttr::AT_EnforceTCB:
8503     handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL);
8504     break;
8505 
8506   case ParsedAttr::AT_EnforceTCBLeaf:
8507     handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL);
8508     break;
8509 
8510   case ParsedAttr::AT_BuiltinAlias:
8511     handleBuiltinAliasAttr(S, D, AL);
8512     break;
8513 
8514   case ParsedAttr::AT_UsingIfExists:
8515     handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL);
8516     break;
8517   }
8518 }
8519 
8520 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
8521 /// attribute list to the specified decl, ignoring any type attributes.
8522 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
8523                                     const ParsedAttributesView &AttrList,
8524                                     bool IncludeCXX11Attributes) {
8525   if (AttrList.empty())
8526     return;
8527 
8528   for (const ParsedAttr &AL : AttrList)
8529     ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
8530 
8531   // FIXME: We should be able to handle these cases in TableGen.
8532   // GCC accepts
8533   // static int a9 __attribute__((weakref));
8534   // but that looks really pointless. We reject it.
8535   if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
8536     Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
8537         << cast<NamedDecl>(D);
8538     D->dropAttr<WeakRefAttr>();
8539     return;
8540   }
8541 
8542   // FIXME: We should be able to handle this in TableGen as well. It would be
8543   // good to have a way to specify "these attributes must appear as a group",
8544   // for these. Additionally, it would be good to have a way to specify "these
8545   // attribute must never appear as a group" for attributes like cold and hot.
8546   if (!D->hasAttr<OpenCLKernelAttr>()) {
8547     // These attributes cannot be applied to a non-kernel function.
8548     if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
8549       // FIXME: This emits a different error message than
8550       // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
8551       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8552       D->setInvalidDecl();
8553     } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
8554       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8555       D->setInvalidDecl();
8556     } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
8557       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8558       D->setInvalidDecl();
8559     } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
8560       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
8561       D->setInvalidDecl();
8562     } else if (!D->hasAttr<CUDAGlobalAttr>()) {
8563       if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
8564         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8565             << A << ExpectedKernelFunction;
8566         D->setInvalidDecl();
8567       } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
8568         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8569             << A << ExpectedKernelFunction;
8570         D->setInvalidDecl();
8571       } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
8572         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8573             << A << ExpectedKernelFunction;
8574         D->setInvalidDecl();
8575       } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
8576         Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8577             << A << ExpectedKernelFunction;
8578         D->setInvalidDecl();
8579       }
8580     }
8581   }
8582 
8583   // Do this check after processing D's attributes because the attribute
8584   // objc_method_family can change whether the given method is in the init
8585   // family, and it can be applied after objc_designated_initializer. This is a
8586   // bit of a hack, but we need it to be compatible with versions of clang that
8587   // processed the attribute list in the wrong order.
8588   if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
8589       cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
8590     Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
8591     D->dropAttr<ObjCDesignatedInitializerAttr>();
8592   }
8593 }
8594 
8595 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
8596 // attribute.
8597 void Sema::ProcessDeclAttributeDelayed(Decl *D,
8598                                        const ParsedAttributesView &AttrList) {
8599   for (const ParsedAttr &AL : AttrList)
8600     if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
8601       handleTransparentUnionAttr(*this, D, AL);
8602       break;
8603     }
8604 
8605   // For BPFPreserveAccessIndexAttr, we want to populate the attributes
8606   // to fields and inner records as well.
8607   if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
8608     handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D));
8609 }
8610 
8611 // Annotation attributes are the only attributes allowed after an access
8612 // specifier.
8613 bool Sema::ProcessAccessDeclAttributeList(
8614     AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
8615   for (const ParsedAttr &AL : AttrList) {
8616     if (AL.getKind() == ParsedAttr::AT_Annotate) {
8617       ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
8618     } else {
8619       Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
8620       return true;
8621     }
8622   }
8623   return false;
8624 }
8625 
8626 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
8627 /// contains any decl attributes that we should warn about.
8628 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
8629   for (const ParsedAttr &AL : A) {
8630     // Only warn if the attribute is an unignored, non-type attribute.
8631     if (AL.isUsedAsTypeAttr() || AL.isInvalid())
8632       continue;
8633     if (AL.getKind() == ParsedAttr::IgnoredAttribute)
8634       continue;
8635 
8636     if (AL.getKind() == ParsedAttr::UnknownAttribute) {
8637       S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
8638           << AL << AL.getRange();
8639     } else {
8640       S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
8641                                                             << AL.getRange();
8642     }
8643   }
8644 }
8645 
8646 /// checkUnusedDeclAttributes - Given a declarator which is not being
8647 /// used to build a declaration, complain about any decl attributes
8648 /// which might be lying around on it.
8649 void Sema::checkUnusedDeclAttributes(Declarator &D) {
8650   ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
8651   ::checkUnusedDeclAttributes(*this, D.getAttributes());
8652   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
8653     ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
8654 }
8655 
8656 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
8657 /// \#pragma weak needs a non-definition decl and source may not have one.
8658 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8659                                       SourceLocation Loc) {
8660   assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
8661   NamedDecl *NewD = nullptr;
8662   if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
8663     FunctionDecl *NewFD;
8664     // FIXME: Missing call to CheckFunctionDeclaration().
8665     // FIXME: Mangling?
8666     // FIXME: Is the qualifier info correct?
8667     // FIXME: Is the DeclContext correct?
8668     NewFD = FunctionDecl::Create(
8669         FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
8670         DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
8671         getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/,
8672         FD->hasPrototype(), ConstexprSpecKind::Unspecified,
8673         FD->getTrailingRequiresClause());
8674     NewD = NewFD;
8675 
8676     if (FD->getQualifier())
8677       NewFD->setQualifierInfo(FD->getQualifierLoc());
8678 
8679     // Fake up parameter variables; they are declared as if this were
8680     // a typedef.
8681     QualType FDTy = FD->getType();
8682     if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
8683       SmallVector<ParmVarDecl*, 16> Params;
8684       for (const auto &AI : FT->param_types()) {
8685         ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
8686         Param->setScopeInfo(0, Params.size());
8687         Params.push_back(Param);
8688       }
8689       NewFD->setParams(Params);
8690     }
8691   } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
8692     NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
8693                            VD->getInnerLocStart(), VD->getLocation(), II,
8694                            VD->getType(), VD->getTypeSourceInfo(),
8695                            VD->getStorageClass());
8696     if (VD->getQualifier())
8697       cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
8698   }
8699   return NewD;
8700 }
8701 
8702 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
8703 /// applied to it, possibly with an alias.
8704 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
8705   if (W.getUsed()) return; // only do this once
8706   W.setUsed(true);
8707   if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
8708     IdentifierInfo *NDId = ND->getIdentifier();
8709     NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
8710     NewD->addAttr(
8711         AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
8712     NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
8713                                            AttributeCommonInfo::AS_Pragma));
8714     WeakTopLevelDecl.push_back(NewD);
8715     // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
8716     // to insert Decl at TU scope, sorry.
8717     DeclContext *SavedContext = CurContext;
8718     CurContext = Context.getTranslationUnitDecl();
8719     NewD->setDeclContext(CurContext);
8720     NewD->setLexicalDeclContext(CurContext);
8721     PushOnScopeChains(NewD, S);
8722     CurContext = SavedContext;
8723   } else { // just add weak to existing
8724     ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
8725                                          AttributeCommonInfo::AS_Pragma));
8726   }
8727 }
8728 
8729 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
8730   // It's valid to "forward-declare" #pragma weak, in which case we
8731   // have to do this.
8732   LoadExternalWeakUndeclaredIdentifiers();
8733   if (!WeakUndeclaredIdentifiers.empty()) {
8734     NamedDecl *ND = nullptr;
8735     if (auto *VD = dyn_cast<VarDecl>(D))
8736       if (VD->isExternC())
8737         ND = VD;
8738     if (auto *FD = dyn_cast<FunctionDecl>(D))
8739       if (FD->isExternC())
8740         ND = FD;
8741     if (ND) {
8742       if (IdentifierInfo *Id = ND->getIdentifier()) {
8743         auto I = WeakUndeclaredIdentifiers.find(Id);
8744         if (I != WeakUndeclaredIdentifiers.end()) {
8745           WeakInfo W = I->second;
8746           DeclApplyPragmaWeak(S, ND, W);
8747           WeakUndeclaredIdentifiers[Id] = W;
8748         }
8749       }
8750     }
8751   }
8752 }
8753 
8754 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
8755 /// it, apply them to D.  This is a bit tricky because PD can have attributes
8756 /// specified in many different places, and we need to find and apply them all.
8757 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
8758   // Apply decl attributes from the DeclSpec if present.
8759   if (!PD.getDeclSpec().getAttributes().empty())
8760     ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
8761 
8762   // Walk the declarator structure, applying decl attributes that were in a type
8763   // position to the decl itself.  This handles cases like:
8764   //   int *__attr__(x)** D;
8765   // when X is a decl attribute.
8766   for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
8767     ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
8768                              /*IncludeCXX11Attributes=*/false);
8769 
8770   // Finally, apply any attributes on the decl itself.
8771   ProcessDeclAttributeList(S, D, PD.getAttributes());
8772 
8773   // Apply additional attributes specified by '#pragma clang attribute'.
8774   AddPragmaAttributes(S, D);
8775 }
8776 
8777 /// Is the given declaration allowed to use a forbidden type?
8778 /// If so, it'll still be annotated with an attribute that makes it
8779 /// illegal to actually use.
8780 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
8781                                    const DelayedDiagnostic &diag,
8782                                    UnavailableAttr::ImplicitReason &reason) {
8783   // Private ivars are always okay.  Unfortunately, people don't
8784   // always properly make their ivars private, even in system headers.
8785   // Plus we need to make fields okay, too.
8786   if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
8787       !isa<FunctionDecl>(D))
8788     return false;
8789 
8790   // Silently accept unsupported uses of __weak in both user and system
8791   // declarations when it's been disabled, for ease of integration with
8792   // -fno-objc-arc files.  We do have to take some care against attempts
8793   // to define such things;  for now, we've only done that for ivars
8794   // and properties.
8795   if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
8796     if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
8797         diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
8798       reason = UnavailableAttr::IR_ForbiddenWeak;
8799       return true;
8800     }
8801   }
8802 
8803   // Allow all sorts of things in system headers.
8804   if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
8805     // Currently, all the failures dealt with this way are due to ARC
8806     // restrictions.
8807     reason = UnavailableAttr::IR_ARCForbiddenType;
8808     return true;
8809   }
8810 
8811   return false;
8812 }
8813 
8814 /// Handle a delayed forbidden-type diagnostic.
8815 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
8816                                        Decl *D) {
8817   auto Reason = UnavailableAttr::IR_None;
8818   if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
8819     assert(Reason && "didn't set reason?");
8820     D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
8821     return;
8822   }
8823   if (S.getLangOpts().ObjCAutoRefCount)
8824     if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
8825       // FIXME: we may want to suppress diagnostics for all
8826       // kind of forbidden type messages on unavailable functions.
8827       if (FD->hasAttr<UnavailableAttr>() &&
8828           DD.getForbiddenTypeDiagnostic() ==
8829               diag::err_arc_array_param_no_ownership) {
8830         DD.Triggered = true;
8831         return;
8832       }
8833     }
8834 
8835   S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
8836       << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
8837   DD.Triggered = true;
8838 }
8839 
8840 
8841 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
8842   assert(DelayedDiagnostics.getCurrentPool());
8843   DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
8844   DelayedDiagnostics.popWithoutEmitting(state);
8845 
8846   // When delaying diagnostics to run in the context of a parsed
8847   // declaration, we only want to actually emit anything if parsing
8848   // succeeds.
8849   if (!decl) return;
8850 
8851   // We emit all the active diagnostics in this pool or any of its
8852   // parents.  In general, we'll get one pool for the decl spec
8853   // and a child pool for each declarator; in a decl group like:
8854   //   deprecated_typedef foo, *bar, baz();
8855   // only the declarator pops will be passed decls.  This is correct;
8856   // we really do need to consider delayed diagnostics from the decl spec
8857   // for each of the different declarations.
8858   const DelayedDiagnosticPool *pool = &poppedPool;
8859   do {
8860     bool AnyAccessFailures = false;
8861     for (DelayedDiagnosticPool::pool_iterator
8862            i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
8863       // This const_cast is a bit lame.  Really, Triggered should be mutable.
8864       DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
8865       if (diag.Triggered)
8866         continue;
8867 
8868       switch (diag.Kind) {
8869       case DelayedDiagnostic::Availability:
8870         // Don't bother giving deprecation/unavailable diagnostics if
8871         // the decl is invalid.
8872         if (!decl->isInvalidDecl())
8873           handleDelayedAvailabilityCheck(diag, decl);
8874         break;
8875 
8876       case DelayedDiagnostic::Access:
8877         // Only produce one access control diagnostic for a structured binding
8878         // declaration: we don't need to tell the user that all the fields are
8879         // inaccessible one at a time.
8880         if (AnyAccessFailures && isa<DecompositionDecl>(decl))
8881           continue;
8882         HandleDelayedAccessCheck(diag, decl);
8883         if (diag.Triggered)
8884           AnyAccessFailures = true;
8885         break;
8886 
8887       case DelayedDiagnostic::ForbiddenType:
8888         handleDelayedForbiddenType(*this, diag, decl);
8889         break;
8890       }
8891     }
8892   } while ((pool = pool->getParent()));
8893 }
8894 
8895 /// Given a set of delayed diagnostics, re-emit them as if they had
8896 /// been delayed in the current context instead of in the given pool.
8897 /// Essentially, this just moves them to the current pool.
8898 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
8899   DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
8900   assert(curPool && "re-emitting in undelayed context not supported");
8901   curPool->steal(pool);
8902 }
8903