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